我在data:date_current和中有两个变量days。而且我有days_get返回当月所有天的方法。我想将days变量定义为,days: this.days_get() 但出现错误,告诉我date_current is undefined.
data
date_current
days
days_get
days: this.days_get()
date_current is undefined
但是,如果我将定义移动days到beforeMount钩子中,一切正常。
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 尚未定义(这发生在数据之后)。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>