退出登录后清理vuex

vue 项目中退出登录后清理 vuex 状态的方法

vuex 目录结构及关键内容

1
2
3
4
5
6
7
src/
store/
getters.js
index.js
modules/
user.js
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// src/store/index.js
...
const modulesFiles = require.context('./modules', true, /\.js$/)
const _initState = {}

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default

// 备份初始状态,用于重置
_initState[moduleName] = deepClone(value.default.state) // 深克隆,自己实现或直接用 lodash 的

return modules
}, {})

const store = new Vuex.Store({
state: {
_initState
},
modules,
getters,
mutations: {
// 定义全局的清理方法
RESET_ALL_STATE(state, payload) {
const initState = deepClone(state._initState)
Object.keys(state).forEach(item => {
if (item !== '_initState') {
state[item] = initState[item]
}
})
}
}
})
...

// src/store/modules/user.js

...
const state = {}

const mutations = {}

const actions = {
...
// user logout
logout({ commit, state, dispatch }) {
return new Promise((resolve, reject) => {
...
// 清理所有状态
commit('RESET_ALL_STATE', null, { root: true })
resolve()
})
},
...
}

export default {
namespaced: true,
state,
mutations,
actions
}