前端开发那些事儿

vuex持久化vuex-persistedstate

2020-11-17  本文已影响0人  A_dfa4

vuex-persistedstate 一个对 localstorage / sessionStorage 操作的vue插件

vue-storage-watcher

安装

npm install --save vuex-persistedstate

配置使用

import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()],
});
// nuxt.config.js
plugins: [
    {src: "~/plugins/vuexPersistence.js", ssr: false}
]
// vuexPersistence.js
import createPersistedState from 'vuex-persistedstate'

export default function ({store}) {
  createPersistedState({
    key:'HUODONG',
    reducer: (vuexState) => {
      return {
        signIn: vuexState.signIn  // store中的signIn模块
      }
    },
  })(store)
}

// 页面取值
import { mapState } from 'vuex'

computed: {
   ...mapState({
      signIn: state => state.signIn
   })
}

自定义存储方式

//  需要使用sessionStorage的情况
plugins: [
    persistedState({ storage: window.sessionStorage })
]
//  使用cookie的情况
import persistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

export default new Vuex.Store({
  // ...
  plugins: [
    persistedState({
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) => Cookies.set(key, value, { expires: 7 }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
})

vuex-persistedstate
js-cookie

上一篇下一篇

猜你喜欢

热点阅读