如何解决数据中的变量在方法中未定义
好吧,就像您说的那样:当您在 data() 中调用 days_get 时, date_current 尚未定义(这发生在数据之后)。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>
解决方法
我在data
:date_current
和中有两个变量days
。而且我有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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。