vuex 持久化状态不会随全局变化而更新

时间:2021-02-19 12:52:40

标签: javascript vuejs2 vuex

我有一个持久化的 vuex 状态,我现在想操作该状态在浏览器刷新时仍然存在,这正是我想要的,但我也想在任何时候让我向您展示代码时通过代码清除它

store.js

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

const persistState = createPersistedState({
  paths: ['firebase','user'],
})

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    ...modules,
  },
  plugins: [persistState],
})

modules/index.js

/** this script will go through your modules and then i will generate an object
 * of each module that will export from store.js
 * */

    import camelCase from 'lodash.camelcase'
    const requireModule = require.context('.', true, /\.js$/)
    const modules = {}
    
    requireModule.keys().forEach((fileName) => {
      if (fileName.match('index.js')) {
        return
      }
    
      const nameSplit = fileName.replace(/(\.\/|\.js)/g, '').split('/')
    
      const [name, sub] = nameSplit
    
      const moduleName = camelCase(name)
    
      const actualFragment = requireModule(fileName)
    
      modules[moduleName] = modules[moduleName] || {}
      modules[moduleName][sub] = actualFragment.default || actualFragment
    })
    
    export default modules

modules/user/actions.js

import router from "@/router/router";
import Request from "@/mixins/BackendRequest";

import {
  USER_REQUEST_START,
  SET_USER,
  USER_REQUEST_ERROR,
  SET_USER_SESSION,
  SET_USER_DATA,
} from "./mutation-types";
import firebase from "firebase/app";
import Vue from "vue";

const actions = {
  setUserData({ commit }, data) {
    commit(SET_USER_DATA, data);
  },
};

export default actions;

modules/user/getters.js

 const getters = {
      user(state) {
        return state
      },
export default getters

modules/user/state.js

const state = {
  loading: false,
  error: null,
  data: {},
  sessionTimeOut: null,
  loggedIn: false,
}

export default state

modules/user/mutations.js

import defaultState from './state'

const mutations = {
  SET_USER_DATA(state, data) {
    if (data === null) {
      state = defaultState
    }
    state = {...state, data}
    console.log(state);
  },
}

export default mutations

这就是我如何称呼我的突变

 this.$store.dispatch('setUserData', null)

上面的变化 SET_USER_DATA/setUserData 是从代码中调用的,并且在函数体内部,console.log() 确实按预期显示了更新的状态,但它没有更新/反映全局任何帮助?

0 个答案:

没有答案