优雅的存储Vuex
2021-08-31 本文已影响0人
JX灬君
Vuex 的 store 接受
plugins
选项,这个选项暴露出每次 mutation 的钩子。Vuex 插件就是一个函数,它接收 store 作为唯一参数:const myPlugin = store => { // 当 store 初始化后调用 store.subscribe((mutation, state) => { // 每次 mutation 之后调用 // mutation 的格式为 { type, payload } }) }
页面中使用
const store = new Vuex.Store({ // ... plugins: [myPlugin] })
Vuex官方提供了插件功能,通过插件plugins实现优雅的存储Vuex
在Vuex中,刷新页面会重置stata数据,一般根据具体业务需求将state数据进行本地化存储
在plugins插件中,通过store.subscribe获取每次mutation的调用
store.subscribe传入两个参数,分别是actions.name和新的state实例
通过插件思想可以将原来没有规范的存储进行改造
新建一个存储数据插件
// 创建 lsPlugin插件 const lsPlugin = () => { // 返回一个函数 return (store) => { // 判断一下本地有没有存储@vuex let loc = JSON.parse(localStorage.getItem('@vuex')) // 如果本地已存储,直接通过Vuex的replaceState将state进行替换 if (loc) { store.replaceState(loc) } // 将数据存放本地 // 通过subscribe订阅 store.subscribe((type, state) => { localStorage.setItem('@vuex', JSON.stringify(state)) }) } }
注入到Vuex构造函数的插件plugins里
plugins: [lsPlugin()]
const store = new Vuex.Store({ state, mutations, plugins: [lsPlugin()] })
实现结果,页面刷新state数据不变