Method record of Vuex reset store

It is a common practice to use Vuex as state management in Vue projects. In essence, Vuex is similar to global variable storage, which is convenient to share among all Vue components, and can also dynamically change the state.

At present Vuex can be used to save the login data to localStorage , so as to avoid login in a short time.

Store localStorage reference: Vue project integration vuex-persistedstate

But Vuex doesn’t seem to consider providing a method to reset or clear the state , you need to implement it yourself.

Clear login data

​ It is troublesome to clean up the store when logging out. The store is in memory. Even if localStorage is deleted, the store data in memory may be written to localStorage again, resulting in logout failure.

Delete localStorage directly

You can delete localStorage directly. After deleting, you need to refresh the page. It seems that the experience is not very good, and the entire page will be refreshed.

 window.localStorage.removeItem(STORAGE_KEY) window.location.reload()

reset store

Still consider starting from the store . The idea of ​​resetting the store is as follows:

  1. Save the initial state in the store when the store is initialized
  2. Add a reset ( __resetStoreState ) method to actions and mutations , and save the reset method name to the reset method list
  3. If there are submodules, recursively process the submodules and repeat step 2
  4. Provide a reset method for external access. The specific logic is to trigger the reset method in the reset method list .
Implementation

The specific code is as follows ( StoreHelper.js ), which depends on lodash library:

 import cloneDeep from 'lodash/cloneDeep' import store from '@/store' import Vuex from 'vuex' const TO_RESET_STORE_STATE_KEYS = [] // 需要清理的Key const RESET_STORE_STATE_KEY = '__resetStoreState' // 内部清理方法名/** * store重置初始化,递归处理子模块,并把需要重置的key保存下来* * @param configData store数据* @param excludeNames 不清理的模块名,有些数据可能需要在注销时也不清理* @param parentModuleKey 模块名拼接,处理子模块*/ export function $createStoreWithResetHandler (configData, excludeNames = [], parentModuleKey = '') { const resetStoreKey = parentModuleKey ? `${parentModuleKey}/${RESET_STORE_STATE_KEY}` : RESET_STORE_STATE_KEY TO_RESET_STORE_STATE_KEYS.push(resetStoreKey) // reset相关key存入数组中if (configData.modules) { Object.keys(configData.modules).forEach(moduleName => { if (excludeNames.indexOf(moduleName) === -1) { const module = configData.modules[moduleName] const newParentModuleKey = parentModuleKey ? `${parentModuleKey}/${moduleName}` : moduleName $createStoreWithResetHandler(module, excludeNames, newParentModuleKey) } }) } if (configData.state) { configData.mutations = configData.mutations || {} configData.actions = configData.actions || {} if (!configData.mutations[RESET_STORE_STATE_KEY]) { const initialState = cloneDeep(configData.state) configData.mutations[RESET_STORE_STATE_KEY] = state => Object.assign(state, cloneDeep(initialState)) } if (!configData.actions[RESET_STORE_STATE_KEY]) { configData.actions[RESET_STORE_STATE_KEY] = ({ commit }) => commit(RESET_STORE_STATE_KEY) } } return configData } /** * 重置store方法* * @returns Promise */ export function $resetStoreState () { // 需要重置的key已经存下来,循环key触发重置const resetResults = TO_RESET_STORE_STATE_KEYS.map(resetKey => store.dispatch(resetKey)) return Promise.allSettled(resetResults) } /** * 包装store,方便使用* * @param configData * @param excludeNames * @returns {Store<unknown>} */ export function $wrapStore (configData, excludeNames = []) { return new Vuex.Store($createStoreWithResetHandler(configData, excludeNames)) } /** * 导出$resetStoreState方法,方便使用* Vue.use(StoreHelper) */ export default { install: (Vue, options = {}) => Object.assign(Vue.prototype, { $resetStoreState }) }
Packaging store to collect data

Wrap the store to collect state data, and related methods that need to trigger reset

store.js default code (remove import ):

 Vue.use(Vuex) export default new Vuex.Store({ state: {}, mutations: {}, actions: {}, modules: { Common: CommonStore, Theme: ThemeStore }, plugins: [createPersistedState()] })

It is also relatively simple to modify the code. Replace new Vuex.Store $wrapStore . If some modules do not need to be reset , they can be filtered out:

 Vue.use(Vuex) Vue.use(StoreHelper) export default $wrapStore({ state: {}, mutations: {}, actions: {}, modules: { Common: CommonStore, Theme: ThemeStore }, plugins: [createPersistedState()] }, ['Common']) // Common模块不要reset
trigger store reset

Trigger a reset where needed, such as logout, and then jump to the login page

 this.$resetStoreState().then(() => { // 跳转到登录页面})

This article is transferred from https://fugary.com/?p=416
This site is only for collection, and the copyright belongs to the original author.