# 【优化】-实现vuex数据持久化插件
我们如果想要vuex的数据持久化,而不是刷新页面就丢失,我们可以使用store.subscribe
语法写一个持久化的插件,这个语法会在每次vuex更新的时候自动执行
function vuexLocal() {
return function(store) {
const local = JSON.parse(localStorage.getItem('vuexdata')) || store.state
store.replace(local)
store.subscribe((mutations, state) => {
const newLocal = _.cloneDeep(state)
localStorage.setItem('vuexdata', JSON.stringify(newLocal )))
})
}
}
//使用
export default new Vuex.Store({
state,
mutations,
getters,
actions,
plugins:[saveLocale]
})
这样的话我们就可以把vuex中的数据存到localstorage
,如果vuex里面没有数据的时候会默认从localstorage
获取,就可以实现vuex持久化啦