[英]Computed property's setter isn't invoked when change model property
I have a field with v-model="data.field"
, and computed property: 我有一个带有v-model="data.field"
的字段,并具有计算属性:
data: {
get() {
console.log("getting value")
return this.$store.getters.data
},
set(value) {
console.log("set data " + value)
this.$store.commit('SET_DATA', value)
}
But this is not working, setter is never called. 但这是行不通的,永远不会调用setter。 However, if we change v-model="data"
, all is working properly. 但是,如果我们更改v-model="data"
,那么一切都将正常工作。 Example: codeopen.io 示例: codeopen.io
Setters are only executed when the variable changed, not when a field inside of them changes. 设置器仅在变量更改时执行,而不在其中的字段更改时执行。 Change your computed property to work directly on the field itself: 更改您的计算属性以直接在字段本身上工作:
data: {
get() {
console.log("getting value")
return this.$store.getters.data.field
},
set(field) {
const value = {...this.$store.getters.data, field}
console.log("set data " + value)
this.$store.commit('SET_DATA', value)
}
And then change your v-model
to: 然后将您的v-model
更改为:
v-model="data"
That's because you're trying to modify the variable store
when you should be modifying the state
instead. 那是因为当您应该修改state
时,您正在尝试修改变量store
。
Note: This is for your store mutations
注意:这是针对您的商店mutations
Change this: 更改此:
SET_ITEM (state, item) {
console.log("set item " + item)
store.item = item
}
to: 至:
SET_ITEM (state, item) {
console.log("set item " + item)
state.item = item
}
You should probably also change the other setter as well. 您可能还应该更改其他设置器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.