tags: ‘vue’, ‘vuex’
categories: ‘vue’, ‘vuex’
vue刷新页面后vuex store的state数据丢失的解决方案
产生原因
其实很简单,因为store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store里面的数据就会被重新赋值。
解决思路
我们监听页面刷新事件,在刷新前将store中的数据存储到localStorage中。每次进入页面的时候先读取localStorage中的值并把它赋给store,这样就保留了刷新前的数据
解决方法
在 App.vue 添加如下代码
<template><div id="app"><router-view></router-view></div></template><script>import store from '@/store/store';export default {store, // 引用created () {// 在页面加载时读取localStorage里的状态信息if (localStorage.getItem("store") ) {this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(localStorage.getItem("store"))))}// 在页面刷新时将vuex里的信息保存到localStorage里window.addEventListener("beforeunload",()=>{localStorage.setItem("store", JSON.stringify(this.$store.state))})console.log(this.$store.state);}}</script>
