详解使用vuex进行菜单管理

2020-06-16 06:24:47易采站长站整理

},
init () {
// 刷新页面重置正确高亮菜单tab
this.activeMenu[this.activeMenuName] = true;
},
},
mounted: {
this.init();
},

其他

对于 vuex 的优化

上文有谈到,实际工作中为了更大程度实现代码复用,对于某个类别的状态管理可以只写一个 mutations ,通过传参(Payload )判断更改内容。还是以 menu 管理为例,可进行下面的优化:

vuex 优化后如下:


const store = new Vuex.Store({
// 其他代码略

mutations: {
// 优化后代码,合并 changeFirstActiveMenu 和 changeSecondActiveMenu
changeActiveMenu (state, menuInfo) {
state[menuInfo.menuHierarchy] = menuInfo.name;
}
}
});

组件 js 部分优化后如下:


methods: {
menuClicked(path) {
// 其他代码略高亮

// 优化后代码:更改一级和二级菜单触发同个 mutation
this.$store.commit("changeActiveMenu", {
menuHierarchy: 'activeFirstMenu',
name: path,
});

this.$store.commit("changeActiveMenu", {
menuHierarchy: 'activeSecondMenu',
name: path,
});

// 其他代码略
},
},