Reference: The solution for vuex's state data loss after refreshing the webpage of vue single page application
1. Cause
ans: Vuex's state storage is responsive. When a Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly. But there is a problem: the stored data of vuex is equivalent to the global variables we defined. After refreshing, the data inside will be restored to the initial state. The data in the store is stored in the running memory. When the page is refreshed, the page will reload the vue instance, and the data in the store will be re-assigned.
2. Solutions
ans: to save the state the data in a local storage: localStorage
sessionStorage
cookie
in
3. Resolution process
-
Choose the right client storage
localStorage
: Permanently stored locally, unless actively deletesessionStorage
: Is stored until the current page is closedcookie
: The valid time you set to store, but the drawback is not easy to read data and to store a large
selectionsessionStorage
on the grounds that:- Vue is a single page application, and the operations are all in a page jump route
sessionStorage
It can be guaranteed thatsessionStorage
the data is empty when the page is opened . If it islocalStorage
, the data of the last opened page will be read
-
How
sessionStorage
to store data in the state- Infeasible solution: Since
state
the data in it is responsive, thesessionStorage
storage has to follow changes. And because vuex stipulates that allstate
data in the data mustmutation
be modified by methods, the first solution is tomutation
modifystate
thesessionStorage
corresponding stored attributes while modifying . But if you want to do this, it is better to use it directlysessionStorage
for state management - Feasible solution : When you click the page refresh,
state
save the data in firstsessionStorage
, and then refresh the page. Bywindow.addEventListener("beforeunload",()=>{ })
monitoring the page refresh,beforeunload
this event is triggered first when the page is refreshed. Inapp.vue
the event listenerbeforeunload
, you can ensure that each page refresh can be triggered.
- Infeasible solution: Since
export default {
name: 'App',
created () {
//在页面加载时读取sessionStorage里的状态信息
if (sessionStorage.getItem("store") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
}
//在页面刷新时将vuex里的信息保存到sessionStorage里
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
}