使用 vuex-persistedstate 使只有一个模块持久化

Making only one module persistent with vuex-persistedstate

我需要使用 vuex-persistedstate 让我的模块之一通过页面刷新保持状态。

现在,当我仅在 user 模块中使用 plugins: [createPersistedState()] 时它不起作用。

plugins: [createPersistedState()] 仅当我在商店的 index.js 中使用它时才有效,但它使所有模块持久化,这不是我想要的。

请问有没有办法配置vuex-persistedstate只使用一个模块?

index.js

//import createPersistedState from 'vuex-persistedstate'
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import workout from './modules/workout'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  getters: {

  },
  mutations: {

  },
  actions: {

  },
  modules: {
    user,
    workout
  },
  //This makes all store modules persist through page refresh
  //plugins: [createPersistedState()]
})
user.js

import { USER } from '../mutation-types'
import createPersistedState from 'vuex-persistedstate'

export default {
    namespaced: true,

    state: {
        darkMode: true
    },

    getters: {
        getDarkMode: state => () => state.darkMode
    },

    actions: {
        toggleDarkMode: ({commit}) => commit(USER.TOGGLE_DARKMODE)
    }

    mutations: {
        [USER.TOGGLE_DARKMODE]: (state) => state.darkMode = !state.darkMode
    },
    //This doesn't work
    plugins: [createPersistedState()]
}

查看 the API docs,您需要将插件配置为仅保留商店的特定子集。

export default new Vuex.Store({
  plugins: [
    createPersistedState({
      paths: ['user'],
    }),
  ],
});

来自上面的文档:

paths <Array>: An array of any paths to partially persist the state. If no paths are given, the complete state is persisted. Paths must be specified using dot notation. If using modules, include the module name. eg: "auth.user" (default: [])