在Vuex存储突变中,是否可以访问吸气剂?考虑下面的例子。
new Vuex.Store({
state: {
question: 'Is it possible to access getters within a Vuex mutation?'
},
mutations: {
askQuestion(state) {
// TODO: Get question from getter here
let question = '';
if (question) {
// ...
}
}
},
getters: {
getQuestion: (state) => {
return state.question;
}
}
});
当然,该示例并没有多大意义,因为我可以question
直接在state
突变内的对象上访问该属性,但是我希望您能看到我正在尝试做的事情。即,有条件地操纵状态。
在突变内,this
is undefined
和state
参数可访问state
对象,而不是商店的其余部分。
关于突变的文档没有提及任何有关此操作的信息。
My guess would be that it's not possible, unless I missed something? I guess the alternative would be to either perform this logic outside of the store (resulting in code duplication) or implementing an action that does this, because actions have access to the entire store context. I'm pretty sure that it's a better approach, that is to keep the mutation focused on what it's actually supposed to do; mutate the state. That's probably what I'll end up doing, but I'm just curious if accessing a getter within a mutation is even possible?
如果有人在寻找简单的解决方案,@ bbugh在这里写出了一种解决方法,只需使变体和吸气剂都使用相同的功能即可: