In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to write vue-router code for dynamically generating navigation menus based on back-end permissions". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to write vue-router code to dynamically generate navigation menus based on back-end permissions.
Catalogue
Vue.js
1. Register the global guard
2. Vuex state management global cache routes
3. Route interception
4. Routing menu
5. Recursive menu vue component
Vue.js
Vue-router
Vuex
1. Register the global guard
Core logic
1. Token authentication (backend) = > token fails to return to the login page
2. Obtain user rights
3. Verify permissions and dynamically add routing menu
Router.beforeResolve registers a global guard. Similar to router.beforeEach, the difference is that the parsing guard is invoked before the navigation is confirmed and after the guard and asynchronous routing components are parsed within all components.
Router.beforeResolve (async (to, from) Next) = > {let hasToken = store.getters ['User/accessToken'] if (! settings.loginInterception) hasToken = true if (hasToken) {if (to.path =' / auth/sign-in') {next ({path:'/'})} else {const hasPermissions = store.getters ['User/permissions'] & & store.getters [' User/permissions']. Length > 0 if (hasPermissions) {next ()} else {try {let permissions if (! constant.loginInterception) {/ / settings.js loginInterception is false Create virtual permission await store.dispatch ('User/setPermissions', [' admin']) permissions = ['admin']} else {permissions = await store.dispatch (' User/getUserInfo')} let accessRoutes = [] accessRoutes = await store.dispatch ('Routes/setRoutes' Permissions) / / add routing router.addRoutes (accessRoutes) next ({... to Replace: true})} catch {await store.dispatch ('User/resetAccessToken')} else {if (settings.routesWhiteList.indexOf (to.path)! =-1) {next ()} else {next (' / auth/sign-in')}} document.title = getPageTitle (to.meta.title)})
Settings.js Global Settings
Export default {/ / whether to enable login interception loginInterception: true, / / routing without token verification routesWhiteList: ['/ auth/sign-in','/ auth/register','/ 401 cache,'/ 404'],} 2, Vuex state management global cache routes
State: global storage of data
Getter: can be understood as computed, which calculates the data
Mutations: synchronous changes to data
Actions: asynchronous changes to data (implementing asynchronous operations)
Module: split store into modules
/ * * @ author Alan * @ description Route Intercept status Management * / import {asyncRoutes, constantRoutes} from'@ / router'import {filterAsyncRoutes} from'@ / Utils/handleRoutes'const state = () > ({routes: [], partialRoutes: []}) const getters = {routes: (state) = > state.routes, partialRoutes: (state) = > state.partialRoutes} const mutations = {setRoutes (state, routes) {state.routes = constantRoutes.concat (routes)}, setPartialRoutes (state) Routes) {state.partialRoutes = constantRoutes.concat (routes)} const actions = {async setRoutes ({commit}, permissions) {const finallyAsyncRoutes = await filterAsyncRoutes ([... asyncRoutes], permissions) commit ('setRoutes', finallyAsyncRoutes) return finallyAsyncRoutes}, setPartialRoutes ({commit}, accessRoutes) {commit (' setPartialRoutes', accessRoutes) return accessRoutes}} export default {namespaced: true, state, getters, mutations, actions} 3, Route interception
/ * * @ author Alan * @ description determines whether the current route contains permission * @ param permissions * @ param route * @ returns {boolean | *} * / export function hasPermission (permissions Route) {if (route.meta & & route.meta.permissions) {return permissions.some ((role) = > route.meta.permissions.includes (role))} else {return true}} / * * @ author Alan * @ description intercepts routes * @ param routes * @ param permissions * @ returns {[]} * / export function filterAsyncRoutes (routes) based on the permissions array Permissions) {const finallyRoutes = [] routes.forEach ((route) = > {const item = {... route} if (hasPermission (permissions, item)) {if (item.children) {item.children = filterAsyncRoutes (item.children, permissions)} finallyRoutes.push (item)}) return finallyRoutes} 4, routing menu
/ * * @ author Alan* @ description Public routing * / export const constantRoutes = [{path:'/ auth', name: 'auth2', component: AuthLayout, children: authChildRoutes (' auth2'), hidden: true / / Hidden menu}, {path:'/', name: 'dashboard', component: VerticleLayout, meta: {title:' Dashboard', name: 'sidebar.dashboard' Is_heading: false, is_active: false, link:', class_name:', is_icon_class: true, icon: 'ri-home-4-line', permissions: [' admin']}, children: childRoutes ('dashboard')}] / * * @ author Alan* @ description Asynchronous routing * / export const asyncRoutes = [{path:' / menu-design' Name: 'horizontal-dashboard', component: HorizantalLayout, meta: {title:' MenuDesign', name: 'sidebar.MenuDesign', is_heading: false, is_active: false, link:', class_name:', is_icon_class: true, icon: 'ri-menu-3-line', permissions: [' admin']} Children: horizontalRoute ('dashboard')}, {path:' / core', name: 'core', component: VerticleLayout, meta: {title:' UI Elements', name: 'sidebar.uiElements', is_heading: false, is_active: false, class_name:', link:'', is_icon_class: true Icon: 'ri-pencil-ruler-line', permissions: [' admin']} Children: coreChildRoute ('core')}] 5. Recursive menu vue component {{$t (item.meta.name)}} {{$t (item.meta.name)}} import List from'. / CollapseMenu' / / its own component import {core} from'.. / .. /.. / config/pluginInit'export default {name: 'List' Props: {items: Array, className: {type: String, default: 'iq-menu'}, open: {type: Boolean, default: false}, idName: {type: String, default:' sidebar'}, accordianName: {type: String, default: 'sidebar'}, sidebarGroupTitle: {type: Boolean, default: true}}, components: {List} Computed: {hideListMenuTitle () {return this.sidebarGroupTitle}}, mounted () {}, methods: {activeLink (item) {return core.getActiveLink (item, this.$route.name)} so far I believe you have a deeper understanding of "how to write vue-router code to dynamically generate navigation menus based on back-end permissions". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.