gpt4 book ai didi

vue.js - vuex 模块 appState 不适用于作为第一个参数传递的模块命名空间

转载 作者:搜寻专家 更新时间:2023-10-30 22:35:57 24 4
gpt4 key购买 nike

如果我尝试按照文档的建议将命名空间作为第一个参数传递,我会得到“undefined”作为值(“test”在模块定义中设置)

...mapState('guest', {
email: state => state.email,
}),

但如果我只是这样做而不将 namespace 作为第一个参数,它会工作得很好

...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: {
}
};

最佳答案

您的 computed...mapState 语法是正确的,因此问题很可能出在调用 fill 突变的方式上。你在命名提交吗?

这是一个 working example .

唯一需要更改的是 state: initialState 应该是 state: Object.assign({}, initialState)

第一种方法将状态设置为对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com