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: 使用展示