解决vuex 数据丢失问题

解决Vuex刷新页面数据丢失的问题

方法1使用第三方库 vuex-persistedstate

  • npm install --save vuex-persistedstate

01 store / index.js 之 localStorage

- 注意点 vuex-persistedstate默认存储在 localStorage之中基本上不需要配置什么
import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
  state: {
    cartList: [],
  },
  mutations: {},
  actions: {},
  // 当state中的值发生改变此时localStorage中的vuex的值会同步把state中的所有值存储起来当页面刷
   新的时候state的值会从localStorage自动获取vuex的value值赋值到state中
  plugins: [createPersistedState()] 
})

02 store / index.js 之 sessionStorage

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
   state: {},
   mutations: {},
   actions: {},
   plugins: [createPersistedState({
       storage:window.sessionStorage  // 同localStorage相同只是将vuex的所有值存储到sessionStorage中
   })]
})

03 store / index.js 之 使用vuex-persistedstate指定需要持久化的state

import createPersistedState from "vuex-persistedstate"

const store = newVuex.Store({
 state: {
  count: 0
},
 mutations: {},
 actions: {},
 plugins: [createPersistedState({
   storage:window.sessionStorage,
   reducer(val)  {
         // 此时当count发生改变的时候就会调用此函数并且val的值为当前state对象return的值为当前本地存储的value值本地存储的key值为vuex
         return {
             count: val.count,
         changeCount: 'aaa'
         }
     }
 })]
}

方法2 把state的数据先缓存到localStorage之中页面刷新的时候拿到数据写入vuex

  • store / index.js
import Vue from 'vue';
import Vuex from 'vuex';
 
Vue.use(Vuex);
 
export default new Vuex.Store{
    state: {
       orderList: [],
       menuList: []
   },
    mutations: {
        orderList(s, d) {
          s.orderList= d;
          window.localStorage.setItem("list",jsON.stringify(s.orderList))
        },  
        menuList(s, d) {
          s.menuList = d;
          window.localStorage.setItem("list",jsON.stringify(s.menuList))
       },
   }
}

  • 页面刷新的时候
    • 通过监听beforeunload事件来进行数据的localStorage存储beforeunload事件在页面刷新时进行触发具体做法是在App.vue的created()周期函数中下如下代码
if (window.localStorage.getItem("list") ) {
    this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
} 
 
window.addEventListener("beforeunload",()=>{
    window.localStorage.setItem("list",JSON.stringify(this.$store.state))
})

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue