我遇到以下问题。
我正在声明数据,我想在之前,当前和之后进行设置。
data () {
return {
notes: {
...
},
view: {
dayCurrent: new Date(),
dayBefore: new Date().setDate(this.view.dayCurrent.getDate() - 1),
dayAfter: new Date().setDate(this.view.dayCurrent.getDate() + 1)
}
}
}
但是一旦我保存了这个,就会出现以下错误
data()中的错误:“ TypeError:无法读取未定义的属性'dayCurrent'”,好像我的视图对象不存在。
这是为什么?我该如何设置并避免这种错误。
答案 0 :(得分:5)
另一种解决方案是在dayCurrent
语句外声明return
并在其他属性中引用它。
data () {
const dayCurrent = new Date();
return {
notes: {
...
},
view: {
dayCurrent: dayCurrent,
dayBefore: new Date().setDate(dayCurrent.getDate() - 1),
dayAfter: new Date().setDate(dayCurrent.getDate() + 1)
}
}
}
答案 1 :(得分:2)
我建议按如下所示初始化已挂接的钩子中的view
属性:
data() {
return {
notes: {
...
},
view: {
dayCurrent: '',
dayBefore: '',
dayAfter: ''
}
}
},
mounted() {
this.view.dayCurrent = new Date();
this.view.dayBefore = new Date(this.view.dayCurrent.getDate() - 1);
this.view.dayAfter = new Date(this.view.dayCurrent.getDate() + 1)
}
new Vue({
el: '#app',
data() {
return {
notes: {
},
view: {
dayCurrent: '',
dayBefore: '',
dayAfter: ''
}
}
},
mounted() {
this.view.dayCurrent = new Date();
let d1 = new Date().setDate(this.view.dayCurrent.getDate() - 1);
this.view.dayBefore = new Date(d1);
let d2 = new Date().setDate(this.view.dayCurrent.getDate() + 1);
this.view.dayAfter = new Date(d2)
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{view.dayBefore}}</p>
<p>{{view.dayCurrent}}</p>
<p>{{view.dayAfter}}</p>
</div>