Vuex中的數據在 F5刷新后 數據消失的問題


有兩種辦法:

利用vuex-persistedstate插件

利用本地存儲 sissionstorage 、 localstorage

    我用到的是本地永久存儲的localstorage (用到axios要先引入import axios from "axios"; 不然肯定會有undefined報錯的喲~)
created() {
    if (
      JSON.parse(              //判斷是否存在本地存儲
        !localStorage.getItem("panghu") ||
          localStorage.getItem("panghu") == "undefined"
      )
    ) {              //不存在本地存儲則請求載入json數據 
      axios.get("/api/panghu").then(data => {
        //請求到的數據是data   下面的代碼表示我調用了vuex中的mutation函數
//將data中的我需要的數據傳入了mutat函數中去了,在那個函數中我將data數據放//入了公共的state中的panghu中去了
        this.$store.commit("increment",data.data.data);
        //以下三條不重要  是我本組件內在賦值給本組件中的變量
        this.home_one = this.$store.state.panghu.home_one;
        this.home_two = this.$store.state.panghu.home_two;
        this.home_three = this.$store.state.panghu.home_three;
         //新建一個胖虎 將共享的state數據賦值給此處的panghu
        let panghu = this.$store.state.panghu;
        //將請求到的數據加入到緩存中去
        localStorage.setItem("panghu", JSON.stringify(panghu));
      });
    } else {
//以下是當緩存中有panghu的數據時,直接加載緩存中的數據到共享的state中
和以上的方法是一樣的
      let panghus = JSON.parse(localStorage.getItem("panghu"));
      this.$store.commit("increment",panghus);
//以下三條不重要
      this.home_one = panghus.home_one;
      this.home_two = panghus.home_two;
      this.home_three = panghus.home_three;
    }
},

補充鈎子函數created的理解: 這個鈎子是組件剛剛創建完成,data等屬性剛綁定
沒有生成DOM的時候
而beforeCreate是data屬性都沒有綁定之前,這時候是不能綁定data中的屬性的

再補充網上大佬的緩存機制 : 在刷新之前緩存:

//補充本地存儲 localStorage
created(){
    //在頁面加載時讀取localStorage里的狀態信息
    localStorage.getItem("userMsg") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userMsg"))));   
    //在頁面刷新時將vuex里的信息保存到localStorage里
    window.addEventListener("beforeunload",()=>{
        localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
    })
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM