search
HomeWeb Front-endJS TutorialHow to use vuex to implement menu management

How to use vuex to implement menu management

Jun 19, 2018 pm 02:36 PM
vuexmenuMenu management

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>
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}`);
},

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

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;
  }
 },
});

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>

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();
},

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;
  }
 }
});

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,
  });

  // 其他代码略
 },
},

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!

Statement
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor