vuex本地持久化插件 vuex-persist

在vue项目中使用vuex本地持久化能更方便我们对数据的管理,不需要写localStorage或cookie等集合方法,统一用store来管理全局数据。

直接上代码

import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersistence from 'vuex-persist'
import Cookies from 'js-cookie'
import { module as userModule, UserState } from './user'
import navModule, { NavigationState } from './navigation'
 
export interface State {
  user: UserState
  navigation: NavigationState
}
 
Vue.use(Vuex)
 
const vuexCookie = new VuexPersistence({
  restoreState: (key, storage) => Cookies.getJSON(key),
  saveState: (key, state, storage) =>
    Cookies.set(key, state, {
      expires: 3
    }),
  modules: ['user'], //only save user module
  filter: (mutation) => mutation.type == 'logIn' || mutation.type == 'logOut'
})
const vuexLocal = new VuexPersistence({
  key: 'vuexbase', // 这里可以自定义存入localStorage的键名,默认vuex
  storage: window.localStorage,
  reducer: (state) => ({ navigation: state.navigation }), //only save navigation module
  filter: (mutation) => mutation.type == 'addNavItem'
})
 
const store = new Vuex.Store({
  modules: {
    user: userModule,
    navigation: navModule
  },
  plugins: [vuexCookie.plugin, vuexLocal.plugin]
})
 
export default store

示例代码展示了 vuex-persist 基本用法,可以cookie、localStorage一起使用
官方地址

原文地址:https://yq.aliyun.com/articles/709850

posted @ 2019-09-26 11:27  鳳舞九天  阅读(1470)  评论(0编辑  收藏  举报