我们假设您想同时使用 v-model 的 2-way binding 和 Vuex store。
您的问题是您希望 Vuex 以严格模式存储
const store = new Vuex.Store({
// ...
strict: true
})
所以你所有的变异都应该通过 Vuex 商店,你可以在 Vue.js 开发工具中看到它。
方法一:我们可以通过使用克隆对象来避免Vuex错误,并使用watcher来提交突变。
const store = new Vuex.Store({
strict: true,
state: {
formdata: [{
label: 'A',
text: 'some text'
},{
label: 'B',
text: 'some other text'
},{
label: 'C',
text: ' this is a text'
}]
},
mutations: {
updateForm: function (state, form) {
var index = state.formdata.findIndex(d=> d.label === form.label);
Object.assign(state.formdata[index], form);
}
}
});
new Vue({
el: '#app',
store: store,
data () {
return {
//deep clone object
formdata: JSON.parse(JSON.stringify(this.$store.state.formdata))
};
},
computed: {
formdata() {
return this.$store.state.formdata
}
},
watch: {
formdata: function(form)
this.$store.commit('updateForm', form);
}
}
})
方法 2:您可以使用计算的 get/set 根据vuex doc 提交您的突变
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}