npm install --save vuex-class
文件目录:
代码展示 index:
import Vue from 'vue';
import Vuex from 'vuex';
// 引入模块
import LoginStore from './modules/LoginStore';
Vue.use(Vuex);
export default new Vuex.Store({
modules: { // 模块
LoginStore
},
state: { // 数据 => 这里的数据是公共数据,各个模块之间相互独立维护自己的数据和方法
sb: 'vuexInde_val'
},
mutations: { // 修改数据
setSb: function (states: any, params: object) {
console.log(params);
states.sb = params;
}
}
});
模块的代码展示: namespaced
import { Commit } from 'vuex';
const state: any = {
token: localStorage.getItem('token') || '',
test: 10
};
const mutations = {
setToken(state: any, token: string): void {
state.token = token;
},
setTest(state: any, token: number): void {
state.test += token;
}
};
export default {
namespaced: true, // namespaced为false的时候,state,mutations,actions全局可以调用,为true,生成作用域,引用时要声明模块名
state,
mutations
};
组件内使用: (目前展示的只是部分,更多的可以去npm上去查看)
I : 按需引入你需要的相应模块
import { State, Getter, Action, Mutation, namespace } from 'vuex-class';
II: 引入命名空间 => namespace(对应store中modules模块响应得到模块)
const LoginStore = namespace('LoginStore');
III: 使用展示