head-img Force's Blog

Vuex刷新后保持state

JavaScript

利用sessionStorage配合保存状态,刷新前sessionStorage赋值给state。

export default {
  name: "app",
  components: {},
  created() {
    // 页面每次刷新加载时候都会去读取sessionStorage里面的vuex状态
   if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign({},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store")) //这里存的是可能经过mutions处理过的state值,是最新的,所以放在最后
        )
      )
    }
    // 在页面刷新之前把vuex中的信息存到sessionStoreage
    window.addEventListener("pagehide", () => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
    });
  }
};
  • this.$store.replaceState(newstate):替换 store 的根状态。
  • Object.assign(target,...source):把多个对象的值复制到目标对象上。

会话历史事件

pageshow事件:在用户访问页面时触发;
pageshow 事件类似于 onload 事件,onload 事件在页面第一次加载时触发, pageshow 事件在每次加载页面时触发,即 onload 事件在页面从浏览器缓存中读取时不触发。

pagehide事件:在用户离开当前网页时触发。
pagehide 事件有时可以替代 unload事件,但 unload 事件触发后无法缓存页面。

转载自:https://www.jianshu.com/p/ca88e0270422

点我评论
打赏本文
二维码


125

文章

14

标签

 访客统计  Update-******