如何为 vuex 命名空间模块状态创建 getter 和 setter



如果我有一个命名空间的 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' //, ...
}
}

我使用 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)
}
}
}

另一种选择是使用mapFields。

我找到了另一种使用Vuex mapStates和mapActions助手的方法。 这稍微啰嗦一些。因此,使用 v 模型绑定方法更好。

顺便说一句:如果您按照ittus的建议使用方法,那么您将使用如下所示的 v 模型绑定:

<input v-model="a" />

使用我使用的其他方法,您将必须进行双向绑定,如下所示:

<input :value="a" @input="updateA" />

如果要使用 v-model 绑定,则代码将如下所示:

// Vuex store 
....
modules: {ModuleA, ...}

// ModuleA of store
export default {
namespaced: true,
states: {
a: '',
},
mutations: {
updateA: (state, value) => state.a = value
},
actions: {
updateA(context, value) { context.commit('updateA', value) }
}
}
// Then in your Component you will bind this Vuex module state as below
new Vue({
store,
computed: {
a: {
get() { this.$store.state.ModuleA.a; }
set(value) {this.updateA(value);}
},
},
methods: {
...mapActions('MyModule', [ updateA ]),
}
})

最新更新