vuex 的数据丢失如何处理?

发布时间 2023-10-26 19:34:27作者: 我就尝一口

方法一:存储在 Local Storage、Session Storage、Index DB等。这些都是浏览器的API,可以将数据存储在硬盘上,做持久化存储。

在初始化 state 数据的时候,从 localStorage 中获取:

state = {
    userInfo: localStorage.getItem('userInfo')
}

由于 localStorage 不是响应式的,需要手动更新,在数据更新的地方,比如 mutations 的方法中,再去把 localStorage 也重新赋值:

mutations: {
  setUserInfd(userInfo) {
      localStorage.setItem(‘userInfo’, userInfo);
  } 
}

方法二引入 vuex-persist 插件,它就是为 Vuex 持久化存储而生的一个插件。不需要你手动存取 storage ,而是直接将状态保存至 cookie 或者 localStorage 中。

 

npm install  vuex-persist -S

 

import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
  storage: window.localStorage
})
 
const store = new Vuex.Store({
  state: { ... },
  mutations: { ... },
  actions: { ... },
  plugins: [vuexLocal.plugin]
})
原文链接:https:
//blog.csdn.net/z858466/article/details/124140897