我有简单的月份选择:
<select v-model="month" v-on:change="dateChanged('month', month)">
<option v-for="(month, index) in months" :value="index">{{ month }}</option>
</select>
Vuex中存储的主要日期对象:
computed: {
...mapGetters(['date']),
month() {
return this.date.format('M') - 1
},
问题是,当我更改月份时,month
值没有改变...选择中的月份在视觉上发生了变化,但该值仍然与之前相同。
最佳答案
这是因为 computed
属性,顾名思义,只能在内部被覆盖,它不是您可以写入的数据存储。如果你想从 VueX 商店填充你的 month
并保持可写性,最好将其写成以下组合:
- 一个watcher监视
date
,并在商店更新时更新内部month
数据 - 只允许写入和读取
月份
的内部数据
示例如下:
// Populate internal store with state data
data: function() {
return {
month: this.date.format('M') - 1
}
},
// Map getter
computed: {
...mapGetters(['date'])
},
// Watch changes to mapped getter
watch: {
date: function(val) {
this.month = this.date.format('M') - 1
}
}
当然,遵循DRY原则,你可能希望将逻辑抽象成一个单独的方法:
methods: {
getMonth: function(month) {
return month.format('M') - 1;
}
},
data: function() {
return {
month: this.getMonth(this.date)
}
},
computed: {
...mapGetters(['date'])
},
watch: {
date: function(val) {
this.month = this.getMonth(val)
}
}
关于javascript - 如何更改 Vue 中的计算对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50207872/