问题描述
我有一个 vuex 文件,其中包含越来越多的 mutator,但我不确定将其拆分为不同文件的正确方法.
I have a vuex file with a growing mass of mutators, but I'm not sure of the correct way of splitting it out into different files.
因为我有:
const store = new Vuex.Store({ vuex stuff })
然后下面是我的主要 Vue 应用程序声明:const app = new Vue({ stuff })
const store = new Vuex.Store({ vuex stuff })
and then below that my main Vue app declaration: const app = new Vue({ stuff })
我很高兴使用 Vue 组件,并且已经拥有很多组件,但这是应用程序的顶级内容,我不知道如何将其分解.任何建议表示赞赏.
I'm happy working with Vue components and have lots of those already, but this is stuff at the top level of the app and I'm not sure how to break it apart. Any advice appreciated.
推荐答案
对于那些想分解 Vuex 文件而不创建更复杂的模块化应用程序结构的人,我认为也可以简单地分解动作、突变并将 getter 放入单独的文件中,如下所示:
For those who would like to break up the Vuex file without creating a more complex modular application structure, I think it is also possible to simply break the actions, mutations and getters into separate files like this:
└── src
├── assets
├── components
└── store
├── store.js
├── actions.js
├── mutations.js
└── getters.js
store.js
import Vuex from 'vuex';
import Vue from 'vue';
import actions from './actions';
import getters from './getters';
import mutations from './mutations';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
someObj: {},
},
actions,
getters,
mutations,
});
actions.js
const actionOne = (context) => {
...
context.commit('PROP1_UPDATED', payload);
};
const actionTwo = (context) => {
...
context.commit('PROP2_UPDATED', payload);
};
export default {
actionOne,
actionTwo,
};
mutations.js
const PROP1_UPDATED = (state, payload) => {
state.someObj.prop1 = payload;
};
const PROP2_UPDATED = (state, payload) => {
state.someObj.prop2 = payload;
};
export default {
PROP1_UPDATED,
PROP2_UPDATED,
};
getters.js
const prop1 = state => state.someObj.prop1;
const prop2 = state => state.someObj.prop2;
export default {
prop1,
prop2,
};
...然后您可以使用通常的 this.$store.dispatch('actionOne')
...
...then you are able to do stuff from within your components as you please using the usual this.$store.dispatch('actionOne')
...
这篇关于如何分解我的 vuex 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!