How do I break up my vuex file?

馋奶兔 提交于 2019-12-31 21:43:52

问题


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.

Because I have:

const store = new Vuex.Store({ vuex stuff }) and then below that my main Vue app declaration: const app = new Vue({ stuff })

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.


回答1:


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,
};

...then you are able to do stuff from within your components as you please using the usual this.$store.dispatch('actionOne') ...




回答2:


You can break them into different modules. That way you can keep all related mutations, getters, state and actions in separate files. The documentation explains it better than I can: https://vuex.vuejs.org/en/modules.html




回答3:


In addition to @bigsee's fine answer, if using an index.js file to export the module:

└── src
    ├── assets
    ├── components
    └── store
          └─ mymodule
              ├── state.js
              ├── actions.js
              ├── mutations.js
              ├── getters.js
              └── index.js

index.js

import state from './state'
import * as getters from './getters'
import * as mutations from './mutations'
import * as actions from './actions'

export default {

  state,
  getters,
  mutations,
  actions
}

getters.js

const getData = state => state.data

export {
  getData
}

Similar with actions, mutations and state files.



来源:https://stackoverflow.com/questions/40564071/how-do-i-break-up-my-vuex-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!