如何为 vuex 命名空间模块状态创建 getter 和 setter
How to create getters and setters for vuex namespaced module state
如果我有一个命名空间的 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 warn]: Computed property "a" was assigned to but it has no
setter.
如何解决?
如果你想做 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-model绑定的方式比较好
// 顺便说一句:如果您使用 ittus
建议的方法,那么您将使用如下所示的 v-model 绑定:
<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 ]),
}
})
如果我有一个命名空间的 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 warn]: Computed property "a" was assigned to but it has no setter.
如何解决?
如果你想做 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-model绑定的方式比较好
// 顺便说一句:如果您使用 ittus
建议的方法,那么您将使用如下所示的 v-model 绑定:
<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 ]),
}
})