方法如下:
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 }
如果目標對象中的屬性具有相同的鍵,則屬性將被源對象中的屬性覆蓋。后面的源對象的屬性將類似地覆蓋前面的源對象的屬性。
-