如果我尝试将命名空间作为第一个参数传递,按照文档的建议,我会得到“undefined”作为值(“test”在模块定义中设置)
...mapState('guest', {
email: state => state.email,
}),
但如果我只是这样做而不将命名空间作为第一个参数,它就可以正常工作
...mapState({
email: state => state.guest.email,
}),
我想使用快捷方式,根据文档,第一个示例应该可以工作......对吗?
https://vuex.vuejs.org/guide/modules.html#binding-helpers-with-namespace
这是我的模块定义:
const initialState = function(){
let state = {
email: null,
};
return state;
};
export default {
namespaced: true,
state: initialState(),
mutations: {
fill(state, data) {
Object.assign(state, data);
},
reset(state) {
Object.assign(state, initialState());
}
},
actions: {
}
};
最佳答案
您的计算...mapState
语法是正确的,因此问题可能出在填充突变的调用方式上。您是否为提交命名?
这是一个working example 。
唯一需要改变的是state:initialState
应该是state:Object.assign({},initialState)
。
第一种方法将 state 设置为对 initialState
对象的引用,因此填充突变中的任何更改都会覆盖 initialState
的值,而重置突变不会有任何影响。
组件
export default {
...
computed: {
...mapState("guest", {
email: state => state.email
})
},
mounted() {
// Call the fill mutation with namespace
this.$store.commit("guest/fill", {
email: "some@email"
});
// Call reset after 2 seconds
setTimeout(() => {
this.$store.commit("guest/reset");
}, 2000);
}
商店
const initialState = {
name: "dummyName",
email: "dummy@initial" // put a value here so we can see if mapState works
};
const store = new Vuex.Store({
modules: {
guest: {
namespaced: true,
state: Object.assign({}, initialState),
mutations: {
fill(state, data) {
Object.assign(state, data);
},
reset(state) {
Object.assign(state, initialState);
}
}
}
}
});
关于vue.js - vuex 模块 appState 不适用于作为第一个参数传递的模块命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56926526/