How to use vuex to implement menu 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, 'userList')">注册</span> <span class="chargeList" @click="menuClicked($event, 'chargeList')">充值</span> <span class="buyList" @click="menuClicked($event, 'buyList')">购买</span> <span class="bangList" @click="menuClicked($event, 'bangList')">到期</span> <span class="withDrawList" @click="menuClicked($event, 'withDrawList')">提现</span> </p>
menuClicked (event, url) { // 当前高亮的 menu 非高亮 const currentActiveLink = this.querySelector('.active'); currentActiveLink.classList.remove('active'); // 当前点击的 menu 高亮 event.target.classList.add('active'); // 路由跳转 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: 'firstMenu1', activeSecondMenu : 'secondMenu1', }, 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('secondMenu1')">secondMenu1</span> </p> <p class="subMenu"> <span :class="{ activeSecondMenu: activeMenu.secondMenu2 }" @click="menuClicked('secondMenu2')">secondMenu2</span> </p> <p class="subMenu"> <span :class="{ activeSecondMenu: activeMenu.secondMenu3 }" @click="menuClicked('secondMenu3')">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: '', secondMenu2: '', secondMenu3: '', }, }; }, 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: 'activeFirstMenu', name: path, }); this.$store.commit("changeActiveMenu", { menuHierarchy: 'activeSecondMenu', 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In Windows 11, the Start menu has been redesigned and features a simplified set of apps arranged in a grid of pages, unlike its predecessor, which had folders, apps, and apps on the Start menu. Group. You can customize the Start menu layout and import and export it to other Windows devices to personalize it to your liking. In this guide, we’ll discuss step-by-step instructions for importing Start Layout to customize the default layout on Windows 11. What is Import-StartLayout in Windows 11? Import Start Layout is a cmdlet used in Windows 10 and earlier versions to import customizations for the Start menu into

One of the most annoying changes that we users never want is the inclusion of "Show more options" in the right-click context menu. However, you can remove it and get back the classic context menu in Windows 11. No more multiple clicks and looking for these ZIP shortcuts in context menus. Follow this guide to return to a full-blown right-click context menu on Windows 11. Fix 1 – Manually adjust the CLSID This is the only manual method on our list. You will adjust specific keys or values in Registry Editor to resolve this issue. NOTE – Registry edits like this are very safe and will work without any issues. Therefore, you should create a registry backup before trying this on your system. Step 1 – Try it

By default, the Windows 11 right-click context menu has an option called Open in Windows Terminal. This is a very useful feature that allows users to open Windows Terminal at a specific location. For example, if you right-click on a folder and select the "Open in Windows Terminal" option, Windows Terminal will launch and set that specific location as its current working directory. Although this is an awesome feature, not everyone finds a use for this feature. Some users may simply not want this option in their right-click context menu and want to remove it to tidy up their right-click context menu.

The steps to implement a menu navigation bar with shadow effect using pure CSS require specific code examples. In web design, the menu navigation bar is a very common element. By adding a shadow effect to the menu navigation bar, you can not only increase its aesthetics, but also improve the user experience. In this article, we will use pure CSS to implement a menu navigation bar with a shadow effect, and provide specific code examples for reference. The implementation steps are as follows: Create HTML structure First, we need to create a basic HTML structure to accommodate the menu navigation bar. by
![How to solve the problem 'Error: [vuex] unknown action type: xxx' when using vuex in a Vue application?](https://img.php.cn/upload/article/000/887/227/168766615217161.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
In Vue.js projects, vuex is a very useful state management tool. It helps us share state among multiple components and provides a reliable way to manage state changes. But when using vuex, sometimes you will encounter the error "Error:[vuex]unknownactiontype:xxx". This article will explain the cause and solution of this error. 1. Cause of the error When using vuex, we need to define some actions and mu
![How to solve the problem 'Error: [vuex] do not mutate vuex store state outside mutation handlers.' when using vuex in a Vue application?](https://img.php.cn/upload/article/000/000/164/168760467048976.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
In Vue applications, using vuex is a common state management method. However, when using vuex, we may sometimes encounter such an error message: "Error:[vuex]donotmutatevuexstorestateoutsidemutationhandlers." What does this error message mean? Why does this error message appear? How to fix this error? This article will cover this issue in detail. The error message contains

Vue2.x is one of the most popular front-end frameworks currently, which provides Vuex as a solution for managing global state. Using Vuex can make state management clearer and easier to maintain. The best practices of Vuex will be introduced below to help developers better use Vuex and improve code quality. 1. Use modular organization state. Vuex uses a single state tree to manage all the states of the application, extracting the state from the components, making state management clearer and easier to understand. In applications with a lot of state, modules must be used

More and more people are experiencing the new and improved Microsoft operating system, but it seems that some of them still prefer the old-school design. There's no doubt that the new context menu brings impressive consistency to Windows 11. If we consider Windows 10, the fact that each application has its own context menu element creates serious confusion for some people. From the Windows 11 transparent taskbar to the rounded corners, this operating system is a masterpiece. In this matter, users across the globe are interested to know how to quickly disable Windows 11 Show More Options menu. The process is pretty simple, so if you're in the same boat, make sure you check it out completely
