刷新页面时保存 vuex 数据

Posted M1n90

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷新页面时保存 vuex 数据相关的知识,希望对你有一定的参考价值。

1. 创建 function

// 刷新页面时恢复 vuex state 数据
export function recoverStoreState(store) {
  // 刷新页面时存储 state
  window.addEventListener(\'beforeunload\', () => {
    localStorage.setItem(\'storeState\', JSON.stringify(store.state));
  });

  // 加载页面时写入 state
  const storeState = localStorage.getItem(\'storeState\');
  if (!storeState) return;
  store.replaceState(JSON.parse(storeState));
  localStorage.removeItem(\'storeState\');
}
 
2. 在 App.vue created 或者 mounted 勾子内调用
mounted() {
    recoverStoreState(this.$store);
},

以上是关于刷新页面时保存 vuex 数据的主要内容,如果未能解决你的问题,请参考以下文章