And*_*ndy 7 vue-component vuex vuejs2 vuex-modules
如果我有一个命名空间的 Vuex 模块,在 Vue 组件中使用这些状态时,如何为该模块中的状态创建 getter 和 setter?
// My component
new Vue({
computed: {
// How do I add setters also below????
...mapState('nameSpacedModA', {
a : state => state.a,
// ...
},
// Following will only add getters..
// How to add setter ???
...mapGetters('nameSpacedModA', {
a: 'a',
b: 'b' //, ...
}
}
Run Code Online (Sandbox Code Playgroud)
我使用 v-model 将“a”绑定到表单上的文本输入,然后当我编辑控件值时,Vue 给出错误:
[Vue 警告]:计算属性“a”已分配给但没有设置器。
如何解决这个问题?
如果你想做 2 种方式绑定,你需要在计算属性中定义 getter 和 setter。(不要忘记定义突变updateA)
<input v-model="a">
// ...
computed: {
a: {
get () {
return this.$store.state.a
},
set (value) {
this.$store.commit('updateA', value)
}
}
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用mapFields