export default new Vuex.Store({
state,
getters,
actions,
mutations,
modules: { // 每个路由对应的 module
page1,
page2,
page3,
page4,
page5
},
plugins: __DEV__ ? [createLogger()] : [],
strict: __DEV__ ? true : false
});
路由 page1 对应的 module 的 state 形如:
// store/modules/page1.js
const state = {
// 列表数据
page1Data: [],
// 标题数据
page1Title: ''
}
这些数据是通过调用后端 api 返回并复制的数据,如果我们在路由改变的时候重置这些数据,那么需要将初始化数据提取出来,并且暴露一个需要重置的标识方法 initState() ,代表路由改变的时候需要重置,当然这个方法名称是个约定,你也可以定义为其他名称。改造后为:
// store/modules/page1.js
// 放置你要重置的数据
const initState = {
page1Data: [],
}// state
const state = {
// 参数解构
...initState,
// 路由改变不想重置的数据
page1Title: '',
initState(){
return initState
}
}
全局 module 配置
定义全局 mutation 事件类型
// store/types.js
export const RESET_STATES = 'resetStates'
定义全局 mutation
// store/mutation.jsimport * as types from './types'
// 检测所有的 state 并把 `initState()` 中的属性重置
function resetState(state, moduleState) {
const mState = state[moduleState];
if (mState.initState && typeof mState.initState === 'function') {
const initState = mState.initState();
for (const key in initState) {
mState[key] = initState[key];
}
}
}
export default {
[types.RESET_STATES](state, payload) {
for (const moduleState in state) {
resetState(state, moduleState);
}
},
}
定义全局 action
// store/action.js
import * as types from './types'export default {
// rest state action
resetStates:function (context, payLoad) {
context.commit(types.RESET_STATES, payLoad);
}
}
路由切换触发重置方法
至此一切准备就绪,只需要在路由改变时触发重置的方法即可,在入口 vue 文件中处理
// components/app.vue
<script>
import {mapState, mapActions} from "vuex"
export default{ methods: {
...mapActions({
resetStates: "resetStates"










