VueX 页面刷新数据同步保存本地
-
理解:页面刷新,VueX 数据保存到本地,渲染时重新获取本地数据。
-
使用:在某组件中添加如下钩子函数。比如 App.vue中
created() {
//在页面加载时读取localStorage里的状态信息
if (sessionStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({},
this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
}
//在页面刷新时将vuex里的信息保存到localStorage里
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
注:
-
this.$store.replaceState() 用于替换 store 的信息(状态合并)。
-
Object.assign(target, ...source) 将source的值 赋给 target,若有重复的数据,则覆盖。其中...表示可以多个source。