最近在用vue寫pc端項目,用vuex來做全局的狀態管理, 發現當刷新網頁後,保存在vuex實例store裏的數據會丟失。
1. 產生原因
因爲store裏的數據是保存在運行內存中的,當頁面刷新時,頁面會重新加載vue實例,store裏面的數據就會被重新賦值。
2. 解決思路直接上代碼
//在app.vue中插入
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
created () {
//在頁面加載時讀取sessionStorage裏的狀態信息
if (sessionStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))));
sessionStorage.removeItem('store');
}
//在頁面刷新時將vuex裏的信息保存到sessionStorage裏
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
小編親測可用完美解決!!!