方法中未定义数据中的变量



我在data中有两个变量:date_currentdays。我有days_get方法,它返回当月的所有天数。我想将days变量定义为days: this.days_get(),但我得到错误,告诉我date_current is undefined

但如果我把days的定义移到beforeMount钩子中,一切都会很好。

我可以在data中定义天数吗?

完整组件代码:

<template>
<div></div>
</template>
<script>
export default {
name: "Calendar",
data(){
return {
date_current: new Date(),
days: this.days_get()
}
},

methods: {
days_get(){
const date_iteration = new Date(this.date_current.getFullYear(), this.date_current.getMonth())
let days = []
while(date_iteration.getMonth() === this.date_current.getMonth()){
days.push(new Date(date_iteration.getFullYear(), date_iteration.getMonth(), date_iteration.getDate()))
date_iteration.setDate(date_iteration.getDate() + 1)
}
return days
}
}
}
</script>
<style scoped></style>

错误:

[Vue warn]: Error in data(): "TypeError: this.date_current is undefined"

正如您所说:当您在data((中调用days_get时,date_current尚未定义(这发生在data之后(。beforeMounted位于数据之后,因此它可以工作,因为那时您定义了date_current。但更好的方法是使用计算属性:

<template>
<div></div>
</template>
<script>
export default {
name: "Calendar",
data(){
return {
date_current: new Date()
}
},

computed: {
days(){
const date_iteration = new Date(this.date_current.getFullYear(), this.date_current.getMonth())
let days = []
while(date_iteration.getMonth() === this.date_current.getMonth()){
days.push(new Date(date_iteration.getFullYear(), date_iteration.getMonth(), date_iteration.getDate()))
date_iteration.setDate(date_iteration.getDate() + 1)
}
return days
}
}
}
</script>
<style scoped></style>

最新更新