插件
Vuex 的 store 接受 plugins 选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 作为唯一参数: 查看更多open in new window
自定义插件
const myPlugin = (store) => {
// 当 store 初始化后调用
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
});
};
// 使用
const store = new Vuex.Store({
// ...
plugins: [myPlugin],
});
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
第三方插件
vuex 持久化插件
- vuex-persistedstate
- npm install vuex-persistedstate --save
import createPersistedState from "vuex-persistedstate"; const store = new Vuex.Store({ // 默认存储到localStorage plugins: [createPersistedState()], });
1
2
3
4
5- 存储到 sessionStorage,配置:
- 还有一个姊妹版
import createPersistedState from "vuex-persistedstate"; const store = new Vuex.Store({ // ... plugins: [ createPersistedState({ storage: window.sessionStorage, }), ], });
1
2
3
4
5
6
7
8
9 - vuex-persist
- npm install --save vuex-persist
import VuexPersistence from 'vuex-persist' const vuexLocal = new VuexPersistence({ storage: window.localStorage }) const store = new Vuex.Store({ state: { ... }, mutations: { ... }, actions: { ... }, plugins: [vuexLocal.plugin] })
1
2
3
4
5
6
7
8
9
10
11