zoukankan      html  css  js  c++  java
  • 解决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 }
        

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

      • 源于

  • 相关阅读:
    MVC-READ5(asp.net web from PK asp.net MVC)
    MVC-READ4
    MVC-READ2
    MVC-READ1
    @@ERROR和@@ROWCOUNT的用法
    JS 对输入框文本正在输入中校验
    CSS 父级方法清除浮动方法
    jquery制作滚动条到一定位置触发
    嵌入式app框架
    开发常用软件
  • 原文地址:https://www.cnblogs.com/mayapony/p/12692101.html
Copyright © 2011-2022 走看看