解决vue 刷新数据丢失的问题

用到的技术

  1. vuex 全局数据
  2. window.addEventListener("beforeunload",()=>{ }) 监听页面刷新
  3. 使用localStorage 临时存储数据

思路:在页面刷新的时候,将vuex中的数据存储到localstorage ,然后刷新结束后再将localstorage里的数赋值给store并清楚localstorage

代码

//js 监听页面alert刷新
    window.addEventListener("beforeunload", () => {
      localStorage.setItem("stateInfo", JSON.stringify(this.$store.state));
    });
    if (localStorage.getItem("stateInfo")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(localStorage.getItem("stateInfo"))
        )
      );
    }

    localStorage.removeItem("stateInfo");
    console.log("名字", this.$store.state);
原文地址:https://www.cnblogs.com/riyueqian/p/13056210.html