Home > Web Front-end > JS Tutorial > body text

How to use vuex to implement menu management

亚连
Release: 2018-06-19 14:36:00
Original
1970 people have browsed it

This article mainly introduces the detailed explanation of using vuex for menu management. Now I will share it with you and give you a reference.

The advantages of vuex can only be revealed in complex state management.

If there are multiple levels of menus in the project, and multiple menus of the same level are distributed in different components, the project will have one and only one highlighted menu at each level at the same time. When the menu jumps, in addition to the routing change, the corresponding menu It also needs to be highlighted (previously restored to the non-highlighted state). This is a perfect scenario for using vuex.

Use DOM operations for simple menu management

The idea behind using DOM for menu management is: when clicking the menu, pass the event object into the event handler , you want the currently highlighted menu to be unhighlighted, and then the clicked menu to be highlighted.

<p class="menu-url">
 <span class="active userList" @click="menuClicked($event, &#39;userList&#39;)">注册</span>
 <span class="chargeList" @click="menuClicked($event, &#39;chargeList&#39;)">充值</span>
 <span class="buyList" @click="menuClicked($event, &#39;buyList&#39;)">购买</span>
 <span class="bangList" @click="menuClicked($event, &#39;bangList&#39;)">到期</span>
 <span class="withDrawList" @click="menuClicked($event, &#39;withDrawList&#39;)">提现</span>
</p>
Copy after login
menuClicked (event, url) {
 // 当前高亮的 menu 非高亮
 const currentActiveLink = this.querySelector(&#39;.active&#39;);
 currentActiveLink.classList.remove(&#39;active&#39;);
 // 当前点击的 menu 高亮
 event.target.classList.add(&#39;active&#39;);
 // 路由跳转
 this.$router.push(`/panel/list/${url}`);
},
Copy after login

Although the menu is highlighted when clicking to switch, there is a bug: each initialization will make the default menu highlighted. If the user manually refreshes the non-default highlighted menu at this time page, it will cause menu highlighting errors (for example, after refreshing the buylist page, the page content still stays on the buylist, but the highlighted menu becomes userlist).

If you want to solve this bug, you need to store the menu status locally (refreshing does not change the storage state). You can choose different solutions for local storage, which will not be discussed here, but it is certain that DOM local storage control The menu-highlighted solution will become difficult to maintain as the project grows larger.

Now is the time for vuex to appear.

Using vuex for menu management

Using vuex for menu management requiresplanning the menu level before development so that it can be allocated in vuexstate and mutations .

Planning Level

Determine which menus in the project are first-level menus, which are second-level menus, and so on... It should be noted here that in order to simplify the operation, menus at the same level are labeled with different names. Name it so that in vuex you don't need to pay attention to which page the menu belongs to, just pay attention to the status. The menu level is usually as follows:

|-root
| |
| |-first-menu1
| |   |- second-menu1
| |   |- second-menu2
| |   |- second-menu3
| |
| |-first-menu2
|    |- second-menu3
|    |- second-menu4
|    |- second-menu5
Copy after login

Allocate `state` and `mutations` in vuex

Menus at different levels occupy one `state` respectively. As for `mutations`, In this example, different `state` corresponds to one `mutations`. In actual work, in order to reduce code reuse, only one `mutations` can be written for the state management of the menu, and the level and level to be changed can be determined by passing parameters. The corresponding menu.

It should be noted that the state of vuex will be re-initialized after the page is refreshed, which is obviously inconsistent with the functions required to manage the menu (except for active triggering, other operations cannot affect the menu). You can change the vuex default life cycle through vuex-persistedstate. The following example code stores the vuex state in a cookie:

js

const store = new Vuex.Store({
 state: {
  // 初始化
  activeFirstMenu: &#39;firstMenu1&#39;,
  activeSecondMenu : &#39;secondMenu1&#39;,
 },
 mutations: {
  // 更改一级菜单
  changeFirstActiveMenu (state, menu) {
   state.activeFirstMenu = menu;
  },
  // 更改二级二级菜单
  changeSecondActiveMenu (state, menu) {
   state.activeSecondMenu = menu;
  }
 },
});
Copy after login

Rendering in the component

Dynamically load the highlighted class in the template and control it through the state in vuex:

<p class="subMenu">
 <span :class="{ activeSecondMenu: activeMenu.secondMenu1 }" @click="menuClicked(&#39;secondMenu1&#39;)">secondMenu1</span>
</p>
<p class="subMenu">
 <span :class="{ activeSecondMenu: activeMenu.secondMenu2 }" @click="menuClicked(&#39;secondMenu2&#39;)">secondMenu2</span>
</p>
<p class="subMenu">
 <span :class="{ activeSecondMenu: activeMenu.secondMenu3 }" @click="menuClicked(&#39;secondMenu3&#39;)">secondMenu3</span>
</p>
Copy after login

There is a trick when writing js: the routing path and the corresponding highlighted menu name should be the same, because the routing jump and highlighting menu is directly related, which can reduce one parameter:

data () {
 return {
  // 初始化
  activeMenu: {
   // menu 名称相同,和对应路由的 path 相同
   secondMenu1: &#39;&#39;,
   secondMenu2: &#39;&#39;,
   secondMenu3: &#39;&#39;,
  },
 };
},
computed: {
 activeMenuName () {
  // 检测 vuex 中 activeSecondMenu 的变化
  return this.$store.state.activeSecondMenu;
 }
},
methods: {
 menuClicked(path) {
  // 取消当前 tab 高亮
  this.activeMenu[this.activeMenuName] = false;

  // 更新 vuex 状态及 menu 高亮
  this.$store.commit("changeSecondActiveMenu", path);
  this.activeMenu[this.activeMenuName] = true;

  // 路由跳转 path 和对应 menu 名称相同 
  this.$router.push(`/somePath/${path}`);
 },
 init () {
  // 刷新页面重置正确高亮菜单tab
  this.activeMenu[this.activeMenuName] = true;
 },
},
mounted: {
 this.init();
},
Copy after login

Others

Optimization of vuex

As discussed above In order to realize code reuse to a greater extent in actual work, you can only write one mutation for a certain category of state management, and determine the change content by passing parameters (Payload). Taking menu management as an example, the following optimization can be performed:

vuex is optimized as follows:

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

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

The component js part is optimized as follows:

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

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

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

  // 其他代码略
 },
},
Copy after login

The above is what I compiled Everyone, I hope it will be helpful to everyone in the future.

Related articles:

How to prevent repeated rendering using React

How to implement the grid-layout function using vue

Detailed introduction to adding drag and drop function to Modal in Bootstrap

How to achieve preview effect in JS

Usage Make a project with three.js

The above is the detailed content of How to use vuex to implement menu management. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template