Vuex 实现插件,实际上类似加中间件,在修改State前后,可以记录state修改时间,state状态等等。
Vuex 插件实现初识
const myPlugin = store => {
// 当 store 初始化后调用
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
})
}
在使用的时候,只需要引用和声明即可:
const store = new Vuex.Store({
// ...
plugins: [myPlugin]
});
Vuex 插件实例-状态比较
Vuex 的 store 接受 plugins 选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 作为唯一参数。
例如我们想比较 state更改前后的状态变化:
import _ from lodash;
const myPluginWithSnapshot = store => {
let prevState = _.cloneDeep(store.state)
store.subscribe((mutation, state) => {
let nextState = _.cloneDeep(state)
// 比较 prevState 和 nextState...
// 保存状态,用于下一次 mutation
prevState = nextState
})
}
// plugin register
const store = new Vuex.Store({
// ...
plugins: process.env.NODE_ENV !== 'production'
? [myPluginWithSnapshot]
: []
})
Vuex 插件实例-Persist 状态
vuex的状态在每次页面刷新后,需要重新获取。如果想保持vuex的状态,我们需要借助浏览器的存储储存state状态。
const myPlugin = store => {
// 当 store 初始化后调用
let localState = JSON.parse(localStorage.getItem('default'));
let newState = Object.assign(store.state, localState );
store.replaceState(newState);
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
let stateStr = JSON.stringify(state);
localStorage.setItem('default', stateStr);
})
}