解决Vuex存储数据之后,刷新页面数据消失

方法如下:

created() {
    console.log(sessionStorage.getItem("store"));
    console.log(sessionStorage.length);
    // 如果sessionStorage中存储了store
    if (sessionStorage.getItem("store")) {
    	// replaceState 替换state根状态(参数为 对象)
    	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))
    })
}

其中使用到的方法:

  • this.$store.replaceState(state: Object)

    • 作用:替换store的根状态,即替换state对象
    • 参数:一个对象
  • Object.assign(target, ...sources)

    • 作用:用于将所有可枚举属性的值从一个或多个源对象 sources 复制到目标对象 target。它将返回目标对象 target。

    • 例如:

      const target = { a: 1, b: 2 };
      const source = { b: 4, c: 5 };
      
      const returnedTarget = Object.assign(target, source);
      
      console.log(target);
      // output: Object { a: 1, b: 4, c: 5 }
      
      console.log(returnedTarget);
      // output: Object { a: 1, b: 4, c: 5 }
      
    • Object.assign({},this.$store.state,JSON.parse(sessionStorage.getItem("store"))) 类似于:

      const o1 = { a: 1, b: 1, c: 1 };
      const o2 = { b: 2, c: 2 };
      const o3 = { c: 3 };
      
      const obj = Object.assign({}, o1, o2, o3);
      console.log(obj); // { a: 1, b: 2, c: 3 }
      

      如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖。后面的源对象的属性将类似地覆盖前面的源对象的属性。

    • 源于

原文地址:https://www.cnblogs.com/mayapony/p/12692101.html