api介绍
https://vuex.vuejs.org/zh/api/#replacestate
vuex支持subscribe方法,只要你的state是通过mutation修改的,那么这里可以监听到store的所有变化。
相比于watch方法,这个方法可以针对某些特定的修改执行特定的操作。
index.js
参考代码
store.subscribe((mutation, state) => {
let oldState = JSON.parse(localStorage.getItem('store'))
let store = oldState && oldState !== '' ? Object.assign(oldState, state) : state
localStorage.setItem('store', JSON.stringify(store))
let reg = generateRegExp(['Cart'])
if (reg.test(mutation.type)) {
if (state.data.shop.id) {
localStorage.setItem(state.data.shop.id, JSON.stringify(state.data.cart))
}
}
})
如何恢复缓存呢
我们可以在app.vue中的created生命周期中调用action中的initStore方法
action.js
initStore ({commit}) {
commit(dataConstant.INIT_STORE)
},
在mutation中
[dataConstant.INIT_STORE] (state) {
if (localStorage.getItem('store')) {
let old = JSON.parse(localStorage.getItem('store'))
if (old.data.version && old.data.version < state.version) {
old.data = Object.assign({}, old.data, state)
} else {
old.data = Object.assign({}, state, old.data)
}
this.replaceState(old) // 替换store的根节点
}
},
PS:上面的replaceState方法也是vue-dev-tools中能实现时间旅行的重要方法
本文介绍如何使用Vuex的subscribe方法监听store变化并自动缓存至localStorage,以及如何在应用启动时从缓存中恢复store状态。通过具体代码示例,展示了如何在创建周期中调用action中的initStore方法来初始化store。
2万+

被折叠的 条评论
为什么被折叠?



