前段时间写项目遇到一个问题,更改代码时页面自动刷新,vuex中的数据丢失,导致需要重新返回赋值的页面,开发起来影响效率,于是想到了vuex的持久化处理。
起初我是这样用的
先下载插件
1
| npm install vuex-persistedstate --save
|
引入插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import persist from 'vuex-persistedstate'
export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules: { }, plugins: [ new persist({ storage: window.localStorage, }), ], })
|
奈何不知道出于什么原因,插件未生效,于是拿起我的百度大法
更换了另一种写法
在App.vue文件里做处理
1 2 3 4 5 6 7 8 9 10
| created() { if (sessionStorage.getItem("store")) { this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem("store")))) } window.addEventListener("beforeunload", () => { sessionStorage.setItem("store", JSON.stringify(this.$store.state)) }) }
|
没错,它成了,百度大法好啊