原创

vuex持久化vuex-persistedstate

vuex可以进行全局的状态管理,但刷新后数据会丢失,使用vuex-persistedstate插件,持久化vuex存储。

安装

npm install vuex-persistedstate --save

使用vuex-persistedstate默认存储到localStorage

src\store\index.js

import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
 state: { ... },
 mutations: { ... },
 actions: { ... },
 plugins: [createPersistedState()]
})

使用vuex-persistedstate存储到sessionStorage

src\store\index.js

import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
 state: { ... },
 mutations: { ... },
 actions: { ... },
 plugins: [createPersistedState({
  storage: window.sessionStorage
 })]
})

使用vuex-persistedstate指定需要持久化的state

src\store\index.js

import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
 state: { ... },
 mutations: { ... },
 actions: { ... },
 plugins: [createPersistedState({
  storage: window.sessionStorage,
  reducer(val){
   return {
    //只存储state中的token
    assessmentData: val.token
   }
  }
 })]
})
正文到此结束