Data problems after F5 to refresh the data in the disappearance of Vuex

There are two ways:

Plug-use vuex-persistedstate

Use of local storage 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;
    }
},

Complementary hook function created to understand: This is the component that you just created hook, data and other attributes just bind
when there is no generation of DOM
and beforeCreate before data attributes are not binding, this time is not binding data attributes in

To add caching online Gangster: cache before refresh:

//补充本地存储 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))
    })
}

Guess you like

Origin www.cnblogs.com/panghu123/p/11746513.html