背景
在前端SPA项目开发中,我们往往会用Vuex来管理共享状态。在庞大的项目中,我们可能会遇到需要reset某一个store或者是全部(比如退出登录)
方案
1.对外抛出一个clearStore方法
2.基于传入的数据,去对应的reset这一个store
具体代码
/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import problem from './modules/problem'
import week from './modules/week'
import library from './modules/library'
import global from './modules/global'
import main from './modules/main'
import final from './modules/final'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
global,
week,
problem,
library,
main,
final
},
getters
})
export default store
// 重置state数据
export function clearState(state, initData) {
Object.keys(state).forEach(key => {
if (!initData[key]) {
delete state[key]
}
})
Object.keys(initData).forEach(key => {
state[key] = initData[key]
})
}
// 清除store
export function clearStore(index) {
if (!store) return
const modules = ['Global', 'Problem', 'Library', 'Week', 'Main']
if (index) {
store.commit('clear' + modules[index])
} else {
modules.forEach(item => {
store.commit('clear' + item)
})
}
}
/store/modules/global.js
import { clearState } from '../index.js'
// 初始化数据
const initState = () => ({
forward: false,
fromPageName: ''
})
const global = {
state: initState(),
mutations: {
setForward(state, forward) {
state.forward = forward
},
setFromPageName(state, fromPageName) {
state.fromPageName = fromPageName
},
clearGlobal(state) {
clearState(state, initState())
}
}
}
export default global
/views/demo.vue
import { clearStore } from '@/store/index.js'
// 重置global的store
clearStore(0)
// 重置所欲模块的store
clearStore()
网友评论