vuex中modules的使用方法--模块化使用vuex

以改文件格式为例

1.index.js


引入vuex,引入模块下的文件one.js,vuex-persistedstate即插件,避免页面刷新state丢失。

代码:

import Vue from 'vue';

import Vuex from 'vuex';

import one from './modules/one';

import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex);

export default new Vuex.Store({

  modules: {

    one

  },

  plugins:[createPersistedState()]

})

2.one.js


定义state,actions,mutations,...并抛出

代码:

const state = {

    info:'hello world',

};

const getters = {

};

const mutations = {

  newVal(state,payload){

    // 修改全局state下的值info

    state.info=payload

  },

};

const actions = {

    changeVal(context, payload){

      //触发mutations里的newVal函数

    context.commit('newVal',payload);

    },

};

export default {

    namespaced: true,

    state,

    getters,

    actions,

    mutations

}

组件中引用修改:

eg:

代码:

你可能感兴趣的:(vuex中modules的使用方法--模块化使用vuex)