正在命名空间存储中调度操作(Vuex/Nuxt)



我在Nuxt SPA中访问命名空间存储中的操作时遇到问题。假设我在存储目录中有一个名为"的存储文件;example.js">

import Vuex from "vuex";
const createStore = () => {
return new Vuex.Store({ 
state: {
forms : [],
},
mutations: {
setForms(state, forms) {
state.forms = forms
}
},
actions: {
setForms(vuexContext, forms) {
vuexContext.commit("setForms", forms)
}
},
getters: {
getForms(state) {
return state.forms
}
}
})
}
export default createStore;

然后在某个页面上,我试图获取数据并将其放入商店:

async fetch(context) {
return axios.get(..)
.then(data => {
context.store.dispatch("example/setForms", data.data) 
})
.catch(e => {
context.error(e);
});

这给了我:

未知操作类型:example/setForms

我缺少什么?

您的example.js有点错误,看起来应该是:

//store/example.js
export const state = () => ({
forms: [],
});
export const mutations = {
setForms(state, forms) {
state.forms = forms;
},
};
export const actions = {
setForms(vuexContext, forms) {
vuexContext.commit("setForms", forms);
},
};
export const getters = {
getForms(state) {
return state.forms;
},
};

并像一样使用它

fetch() {
return axios
.get(...)
.then((data) => {
this.$store.dispatch("example/setForms", data.data);
})
.catch((e) => {
context.error(e);
});
},

请将namespaced: true添加到您的商店中。因此:

const moduleA = { 
namespaced: true,
state: {
forms : [],
},
mutations: {
setForms(state, forms) {
state.forms = forms
}
},
actions: {
setForms(vuexContext, forms) {
vuexContext.commit("setForms", forms)
}
},
getters: {
getForms(state) {
return state.forms
}
}
}

const store = new Vuex.Store({
modules: {
a: moduleA
}
});

export default store;

因此您可以将其用作$this.store.commit("a/setForms");