How to solve the problem of data loss when using vuex for global state management in the project?

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 cookiein

3. Resolution process

  1. Choose the right client storage

    • localStorage : Permanently stored locally, unless actively delete
    • sessionStorage: Is stored until the current page is closed
    • cookie: The valid time you set to store, but the drawback is not easy to read data and to store a large
      selection sessionStorageon the grounds that:
    • Vue is a single page application, and the operations are all in a page jump route
    • sessionStorageIt can be guaranteed that sessionStoragethe data is empty when the page is opened . If it is localStorage, the data of the last opened page will be read
  2. How sessionStorageto store data in the state

    • Infeasible solution: Since statethe data in it is responsive, the sessionStoragestorage has to follow changes. And because vuex stipulates that all statedata in the data must mutationbe modified by methods, the first solution is to mutationmodify statethe sessionStoragecorresponding stored attributes while modifying . But if you want to do this, it is better to use it directly sessionStoragefor state management
    • Feasible solution : When you click the page refresh, statesave the data in first sessionStorage, and then refresh the page. By window.addEventListener("beforeunload",()=>{ })monitoring the page refresh, beforeunloadthis event is triggered first when the page is refreshed. In app.vuethe event listener beforeunload, you can ensure that each page refresh can be triggered.
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))
    })
  }
}

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108609104