search
HomeWeb Front-endJS TutorialDetailed explanation of the steps to implement dynamic permission routing menu with vue addRoutes

This time I will bring you a detailed explanation of the steps to implement dynamic permission routing menu with vue addRoutes. What are the precautions for vue addRoutes to implement dynamic permission routing menu. Here is a practical case, let’s take a look.

Requirements

Recently took over a backend management system, and it is necessary to realize the effect of pulling the navigation menu from the backend; according to the different permissions of the logged in user, The pulled-out navigation menu is also different, and the operable interface is also different.

Question

Because the background management system is prepared to use vue vue-router element-ui vuex, but the single-page application The vue-router has been instantiated and injected into the vue instance before entering the page, so there is no way to re-customize the route when entering the login page. After a lot of searching, I found that vue-router provided the addRoutes method to add routes in version 2.0, and a glimmer of hope appeared.

After a lot of hard work, the function was finally realized. I recorded it for easy review. I also hope it can help comrades who have the same needs.

Ideas

1. First configure a fixed routing address locally, such as login and 404 pages, as follows:

import Vue from 'vue'
import Router from 'vue-router'
import store from '@/vuex/store'
Vue.use(Router)
let router = new Router({
 routes: [
  {
   path: '/login',
   name: 'login',
   meta: {requireAuth: false},
   // 模块使用异步加载
   component: (resolve) => require(['../components/login/login.vue'], resolve)
  }]
})
// 拦截登录,token验证
router.beforeEach((to, from, next) => {
 if (to.meta.requireAuth === undefined) {
  if (store.state.token) {
   next()
  } else {
   next({
    path: '/login'
   })
  }
 } else {
  next()
 }
})
export default router

Only after configuring these fixed routes can we get to the login page, otherwise we will not be able to continue.

2. Then the important step is to agree with the back-end veteran on the permission menu list information that needs to be returned; first, let’s analyze the routing structure we need. Here I take my own routing as an example. . If I define the route directly myself, it will have the following structure:

let router = new Router({
 routes: [
  {
   path: '/login',
   name: 'login',
   meta: {requireAuth: false},
   component: (resolve) => require(['../components/login/login.vue'], resolve)
  },
  {
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/layout',
    component: (resolve) => require(['../layout.vue'], resolve),
    children: [
      {
        path: 'index', 
        meta: {
          type: '1',    //控制是否显示隐藏 1显示,2隐藏
          code: 00010001, // 后面需要控制路由高亮
          title: '首页',  // 菜单名称
          permissonList: [] // 权限列表
        }
        component: (resolve) => require(['@/components/index/index.vue'], resolve)
      },
      {
      ...
      }   
    ]
  }]
})

According to the above structural analysis, in fact, the route that really requires dynamic configuration is actually under /layout The children part, so the backend needs to return to us an array containing all routes.

In the returned data, the rootList is a list of first-level navigation. Navigation actually does not have routing function. It is only used as a trigger to switch secondary menu. SubList is the routing information we really need.

3. After getting the permission routing information, we need to process the data locally and assemble it into the data we need:

// 登录
   login () {
    let params = {
     account: this.loginForm.username,
     password: encrypt(this.loginForm.password)
    }
    this.loading = true
    this.$http.post(this.$bumng + '/login', this.$HP(params))
     .then((res) => {
      this.loging = false
      console.info('菜单列表:', res)
      if (res.resultCode === this.$state_ok) {
       // 合并一级菜单和二级菜单,便于显示
       let menus = handleMenu.mergeSubInRoot(res.rootList, res.subList)
       // 本地化处理好的菜单列表
       this.saveRes({label: 'menuList', value: menus})
       // 根据subList处理路由
       let routes = handleMenu.mergeRoutes(res.subList)
       // 本地化subList,便于在刷新页面的时候重新配置路由
       this.saveRes({label: 'subList', value: res.subList})
       // 防止重复配置相同路由
       if (this.$router.options.routes.length  {
      this.loging = false
      console.error('错误:', err)
     })
   },

Methods for processing menu lists and subLists: mergeSubInRoot and mergeRoutes

const routes = [
 {
  path: '/',
  redirect: '/layout'
 },
 {
  path: '/layout',
  component: (resolve) => require(['../layout.vue'], resolve),
  children: []
 }
]
export default {
 /**
  * 合并主菜单和子菜单
  * @param: rootList [Array] 主菜单列表
  * @param: subList [Array] 子菜单
  * */
 mergeSubInRoot (roots, subs) {
  if (roots && subs) {
   for (let i = 0; i  require([`@/components/${subs[i].component}.vue`], resolve),
     meta: {
      type: subs[i].type,
      code: subs[i].code,
      title: subs[i].name,
      permissionList: subs[i].permissionList
     }
    }
    routes[1].children.push(temp)
   }
  }
  return routes
 }
}

So far we have successfully configured permission routing into local routing. My system login is as follows

Follow-up optimization

1. Menu list display and secondary navigation switching:

<template>
  <p>
   <el-menu>
    <el-menu-item>
     <i></i>
     <span>{{item.name}}</span>
    </el-menu-item>
   </el-menu>
  </p>
</template>
<script>
 import {mapState, mapMutations} from &#39;vuex&#39;
 export default {
  name: &#39;menu&#39;,
  data () {
   return {
    msg: &#39;Welcome to Your Vue.js App&#39;
   }
  },
  computed: {
   ...mapState([&#39;menuList&#39;]),
   activeCode () {
     // 通过code保证在切换字路由的情况下一级路由也是高亮显示
    return this.$route.meta.code.substring(0, 4)
   }
  },
  methods: {
   ...mapMutations([&#39;saveRes&#39;]),
   // 切换二级路由
   switchSubMenu (route) {
    console.info(&#39;路由:&#39;, route)
    if (route.actUrl !== &#39;index&#39;) {
     // 用currentSubMenu控制二级路由数据 
     this.saveRes({label: &#39;currentSubMenu&#39;, value: route.children})
     this.$router.push(`/layout/${route.children[0].actUrl}`)
    } else {
     // 不存在二级路由隐藏二级 
     this.saveRes({label: &#39;currentSubMenu&#39;, value: &#39;&#39;})
     this.$router.push(`/layout/${route.actUrl}`)
    }
   }
  },
  filters: {
   splitCode (code) {
    return code.substring(0, 4)
   }
  }
 }
</script>

2. Prevent refresh routing from being lost; since the single-page application will be re-initialized during refresh, all All configured routes will be lost. Once you return to before liberation, only locally configured routes can be jumped. At this time, we can execute the following code in app.vue (ps: no matter where the refresh is performed, app.vue will be executed):

<script>
 import {decrypt} from &#39;@/libs/AES&#39;
 import handleMenu from &#39;@/router/handleMenu&#39;
 export default {
  name: &#39;app&#39;,
  created () {
   // 当this.$router.options.routes的长度为1,且本地缓存存在菜单列表的时候才重新配置路由
   if (this.$router.options.routes.length <= 1 && sessionStorage.getItem(&#39;subList&#39;)) {
    let subList = JSON.parse(decrypt(sessionStorage.getItem(&#39;subList&#39;)))
    let routes = handleMenu.mergeRoutes(subList)
    this.$router.addRoutes(routes)
    // this.$router不是响应式的,所以手动将路由元注入路由对象
    this.$router.options.routes.push(routes)
   }
  }
 }
</script>

In this way, even if refreshed, the routing will be reconfigured.

3. Regarding page button level control, you can customize a command to do this. Because we have put the permission list into the meta object of the corresponding route, we can easily go back to the permissions that the current user has on the current page on each page

Refer to the official document custom instructions

Conclusion

After finishing the work, thanks to the addRoutes method added to vue-router2, otherwise

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for php to generate a random string of custom length

php image cropping and thumbnail usage examples

The above is the detailed content of Detailed explanation of the steps to implement dynamic permission routing menu with vue addRoutes. 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
如何在 Windows 11 上检查 NAT 类型如何在 Windows 11 上检查 NAT 类型Apr 13, 2023 pm 10:22 PM

延迟死亡是在线游戏玩家可能发生的最糟糕的事情。但是您知道吗,它并不总是由网速慢引起的?与流行的看法相反,这通常是您的 NAT 类型的问题,并且不会通过简单地致电您的互联网服务提供商来解决。什么是 NAT,它有什么作用?网络地址转换或 NAT 是一种网络系统,它提供了一种将本地 IP 地址修改为更广泛的互联网地址的方法。这就是您能够在同一本地网络上的许多设备上使用单个 IP 地址的方式。NAT 作为路由器的一部分,基本上将您的路由器变成本地网络和更广泛的互联网之间的中间管理者。但是,不只有一个 N

Wi-Fi 没有有效的 IP 配置:如何修复Wi-Fi 没有有效的 IP 配置:如何修复Apr 13, 2023 pm 06:22 PM

重启你的电脑和路由器你知道该怎么做; 如果您致电 ISP 技术支持,他们会要求您重新启动网络硬件。这是有充分理由的,因为重新启动您的 PC 将清除可能与您的连接发生冲突的正在运行的应用程序和缓存。重新启动(反弹)您的路由器(通常是包含路由器和调制解调器的组合单元)将清除其缓存并重新建立可靠的在线连接。如果您还有一个单独的调制解调器,也请重新启动它。通过拔下电源按钮30 秒重新启动路由器,然后将其重新插入。启动路由器后,重新启动 PC 并查看您是否重新获得稳定的 Wi-Fi 连接。重新启用 Wi-

使用设置应用程序或路由器在 iPhone 上查找 Mac 地址的 5 大方法使用设置应用程序或路由器在 iPhone 上查找 Mac 地址的 5 大方法Apr 13, 2023 pm 05:46 PM

任何连接到互联网的设备都有两种类型的地址——物理地址和互联网地址。虽然 Internet 地址在全球范围内定位设备,但物理地址有助于识别连接到本地网络的特定设备。这个物理地址在技术上称为 MAC 地址,如果您想知道您的 iPhone 是否有一个,是的,所有手机(包括 iPhone)都有自己独有的 MAC 地址。什么是 MAC 地址?媒体访问控制或 MAC 地址是一种独特的指标,用于从连接到同一网络的其他设备中识别您的设备。如果您拥有可以连接到互联网的设备,它将注册一个 MAC 地址。此地址由占

解决“Windows 11 上的 DNS 服务器未响应”问题的 12 种方法解决“Windows 11 上的 DNS 服务器未响应”问题的 12 种方法Apr 15, 2023 pm 10:46 PM

什么是DNS?DNS是域名系统的首字母缩写词,它是一个分散的命名系统,所有计算机、服务器和更多试图连接到互联网的设备都使用它。DNS有助于识别您的PC和发送到它的流量,系统会自动破译并显示必要的信息。为什么我在Windows11上收到“DNS服务器没有响应”?这个问题可能有很多原因。有时,Windows可能会将网络问题误认为是DNS问题,而有时它很可能是第三方应用程序干扰了您的网络。最近对AVG防病毒软件的更新似乎是导致此问题的主要原因,禁用该更新似乎可以解决大多数用户的此问题

linux添加路由命令是什么linux添加路由命令是什么Jan 04, 2023 pm 01:49 PM

linux添加路由命令是“route”,linux添加路由的方法是:1、在“/etc/rc.local”里添加“route add -net 192.168.2.0/24 gw 192.168.3.254”;2、在“/etc/sysconfig/network”里添加“GATEWAY=gw-ip”到末尾;3、在“static-router”添加“any net ...”即可。

如何在 Windows 11 / 10 上解决无互联网安全问题如何在 Windows 11 / 10 上解决无互联网安全问题May 11, 2023 pm 10:07 PM

在Windows11/10计算机上看到的与互联网连接相关的问题之一是“无互联网,安全”错误消息。基本上,此错误消息表明系统已连接到网络,但由于连接存在问题,您无法打开任何网页并接收数据。在Windows中连接到任何网络时可能会遇到此错误,最好是在通过不在附近的WiFi路由器连接到Internet时。通常,当您检查系统托盘右下方的无线图标时,会看到一个黄色的小三角形,当您单击它时,会显示无Internet,安全消息。出现此错误消息没有具体原因,但配置设置的更改可能会导致您的路由器无法连接

用 NTP 时间服务器错误修复路由器失去联系的 3 种方法用 NTP 时间服务器错误修复路由器失去联系的 3 种方法May 22, 2023 pm 03:43 PM

连接和WiFi的问题可能会非常令人沮丧并显着降低生产力。计算机使用网络时间协议(NTP)进行时钟同步。在大多数情况下(如果不是全部),您的笔记本电脑使用NTP来跟踪时间。如果您的服务器因NTP时间服务器错误消息而失去联系,请阅读本文到底以了解如何修复它。当路由器的时间设置不正确时会发生什么?路由器的性能通常不受时间设置错误的影响,因此您的连接可能不会受到影响。但是,可能会出现一些问题。这些包括:使用路由器作为本地时间服务器的所有小工具的时间不正确。路由器日志数据中的时间戳将是错误的。如果由于

修复:以太网在 Windows 11 中没有有效的 IP 配置修复:以太网在 Windows 11 中没有有效的 IP 配置Apr 14, 2023 am 10:01 AM

多年来,关于使用以太网还是 Wi-Fi 的争论一直在激烈进行,每一种都比另一种具有一定的优势。但是,两者都不是完全没有错误的。常见的一种情况是以太网在 Windows 11中没有有效的 IP 配置。该错误并不常见,但遇到时,用户无法访问 Internet。这使得有效地对其进行故障排除变得更加重要。但是还有一个重要的问题需要事先回答,即为什么以太网在 Windows 11中没有有效的 IP 配置?因此,让我们带您了解它的答案以及最有效的错误修复方法。为什么以太网在 Windows 11 中没有有效

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor