- 页面在进行刷新的时候,Vuex的状态会丢失,也即Vuex被还原到了最初的状态。原因是因为Vuex状态被保存到浏览器缓存中,当页面进行了刷新,缓存没了,最新状态自然也就丢失了,还原到了最初状态。
- 解决思路是:监听页面刷新事件,在页面刷新的前一刻,将Vuex最新状态保存到sessionStorage中,在页面刷新后,再从sessionStorage中拿到之前Vuex最新的状态,替换到(replacestate)Vuex中即可。
-
//在App根页面中 <script> export default { name : 'App', created(){ //从sessionStorage中取值,放到Vuex中 if(sessionStorage.getItem('store')){ this.$store.replaceState(JSON.parse(sessionStorage.getItem('store'))); } //监听页面刷新事件,将Vue最新状态值保存到sessionStorage中 window.addEventListener('beforeunload',() => { sessionStorage.setItem('store',JSON.stringify(this.$store.state)); }); }, } </script>
Vue---Vuex状态丢失解决方案
猜你喜欢
转载自blog.csdn.net/qq_39115469/article/details/107877486
今日推荐
周排行