The main idea of ​​​​dynamically setting routing permissions in Vue

The main idea of ​​​​dynamically setting routing permissions in Vue

I have seen some dynamic routing settings on the Internet before, but they are not very compatible with the current project, so I implemented one myself. The main idea is:

1. Bind the id when configuring the route. After the backend development is completed, just synchronize the id with the backend. This id is unique and unchanged. The route address and icon can be found based on this id.

const routerArr = [
 {
 path: '',
 name: '',
 component: () => import( /* webpackChunkName: "strategiesMaintain" */ '@/components/Layout/Index'),
 meta: {
 requireAuth: true,
 id: 1,
 icon: 'iconzhanghuguanli',
 title: 'Route 1'
 },
 children: [{ 
 path: '/verificationLog',
 name: 'VerificationLog',
 component: () => import( /* webpackChunkName: "verificationLog" */ '@/views/auditManage/verificationLog'),
 meta: {
 requireAuth: true,
 id: 101,
 icon: 'icon-disanfangyanzhengrizhi',
 title: 'Route 11'
 }
 }, {
 path: '/systemLog',
 name: 'SystemLog',
 component: () => import( /* webpackChunkName: "systemLog" */ '@/views/auditManage/systemLog'),
 meta: {
 requireAuth: true,
 id: 102,
 icon: 'icon-xitongcaozuorizhi',
 title: 'Route 12'
 }
 }]
 }
];

export default routerArr;

2. Set the connection between the local route and the route from the backend, mainly based on the id binding route address and iconClass

import routerModules from "@/router/modules";
import {http} from '@/utils/http'
import store from '@/store';
import { Message } from 'element-ui'

const formateResData = (val) =>{ // Format routing data const obj = {};
 const fn = (arr)=>{
  for(let i = 0,item;item = arr[i++];){
  obj[item['meta']['id']] = {
   path: item['path'],
   iconClass: item['meta']['icon']
  };
  if (item.children && item.children.length > 0) {
   fn(item.children);
  }
  }
 }
 fn(val);
 return obj;
};

const MAPOBJ = formateResData(routerModules);
const dealWithData = (navData) => { // Process menu data let firstLink = "";
 const navIdArr = [];
 const fn = (arr) => {
  for (let i = 0,item;item = arr[i++];) {
  item['iconClass'] = MAPOBJ[item.id].iconClass;
  item['linkAction'] = MAPOBJ[item.id].path;
  navIdArr.push(item.id);
  if (!firstLink && !item.subMenu) { // Set the default jump firstLink = item['linkAction'];
  }
  if (item.subMenu && item.subMenu.length > 0) {
   fn(item.subMenu);
  }
  }
 }
 fn(navData);
 return {navData,navIdArr,firstLink};
};

let navIds = [];

const getNav = async (to={},from={},next=()=>{})=>{ // Get navigation data const {code,data} = await http("/menu/list", {}, "GET"); // Get menu data // const data = require("@/mock/api/menuData"); // Use mock data const {navData,navIdArr,firstLink} = dealWithData(data);
 store.commit('setNavData', navData);
 navIds = navIdArr;
 if(to.fullPath == '/index'){ // Login or return to homepage next(firstLink);
 }else { // Refreshif(navIds.indexOf(to.meta.id) == -1){ // The backend did not return the menuMessage.error('The menu does not exist or has no permission');
  return;
 }
 next();
 }
}

export const setGuard = (to={},from={},next=()=>{}) =>{ // Set permissions if(navIds.length === 0){ // Menu data has not been obtained yet getNav(to,from,next);
 }else { // Get the menu data if(navIds.indexOf(to.meta.id) == -1){ // The backend did not return the menu Message.error('The menu does not exist or there is no permission');
  return;
 }
 next();
 }
}

3. Introduce configuration in mainjs

router.beforeEach((to, from, next) => {
 let token = wlhStorage.get("authorization");
 if (to.path == "/login") {
 storage.clear(); // Clear cache next();
 } else {
 if (to.meta.requireAuth && token) { // Login setGuard(to,from,next);
 } else { // Not logged in next("/login");
 }
 }
})

Summarize

This is the end of this article about dynamically setting routing permissions in Vue. For more relevant content about dynamically setting routing permissions in Vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Two methods of Vue permission control (route verification)
  • Sample code about Vue's routing permission management
  • How to set login permissions for routes in Vue
  • Vuex displays different routing list functions according to different user permissions
  • Vue routing guard, an example of limiting access rights to front-end pages
  • How to set up Vue routing guards and page login permission control (two methods)
  • Summary of examples of methods for implementing Vue permission routing
  • Vue custom instructions and dynamic routing to achieve permission control
  • vue-router controls the implementation of routing permissions
  • Implementation code of Vue routing permission verification function

<<:  Java example code to generate random characters

>>:  Native JavaScript to implement random roll call table

Recommend

Comprehensive explanation of CocosCreator hot update

Table of contents Preface What is Hot Change Coco...

The easiest way to make a program run automatically at startup in Linux

I collected a lot of them, but all ended in failu...

Native JS to achieve blinds special effects

This article shares a blinds special effect imple...

Summary of MySQL Architecture Knowledge Points

1. Databases and database instances In the study ...

HTML+CSS to achieve drop-down menu

1. Drop-down list example The code is as follows:...

The principle and direction of JavaScript this

How to determine what this points to? ①When calle...

Implementation code of short video (douyin) watermark removal tool

Table of contents 1. Get the first link first 2. ...

How to view files in Docker image

How to view files in a docker image 1. If it is a...

HTML table markup tutorial (16): title horizontal alignment attribute ALIGN

By default, the table title is horizontally cente...

Example of MySQL auto-increment ID exhaustion

Display Definition ID When the auto-increment ID ...

How to use mysqldump for full and point-in-time backups

Mysqldump is used for logical backup in MySQL. Al...

Vue implementation counter case

This article example shares the specific code of ...

How to use linux commands to convert and splice audio formats

Install FFmpeg flac eric@ray:~$ sudo apt install ...

How to use ss command instead of netstat in Linux operation and maintenance

Preface When operating and managing Linux servers...

CSS horizontal centering and limiting the maximum width

A CSS layout and style question: how to balance h...