yangxuanLL

Vuex持久化插件-解决刷新数据消失的问题(vuex-persistedstate)

利用vuex进行全局状态管理的时候,刷新页面数据会丢失,如何解决这样的问题呢?可以通过插件vuex-persistedstate来解决。

1、安装

npm install vuex-persistedstate --save

2、引入及配置

在store的index.js文件中
import createPersistedState from 'vuex-persistedstate';

const store = new Vuex.Store({
  ...
  plugins: [createPersistedState()]
})


以上默认是以localStorage的方式存储,如果想用sessionStorage方式存储,请使用以下方式:
const store = new Vuex.Store({
  ...
  plugins: [createPersistedState({
      storage: window.sessionStorage
  })]
})

   默认持久化所有state,要想持久化指定state,配置如下:

 

const store = new Vuex.Store({
  ...
  plugins: [createPersistedState({
      storage: window.sessionStorage,
    reducer(val) {
          return {
            // 只储存state中的user
            user: val.user
          }
      }
  })]
})

 

posted on 2019-06-21 15:32  yangxuanLL  阅读(3246)  评论(0编辑  收藏  举报

导航