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

Details of Linux file descriptors, file pointers, and inodes

Table of contents Linux--File descriptor, file po...

JavaScript Canvas draws dynamic wireframe effect

This article shares the specific code of JavaScri...

Tutorial on installing DAMO database on Centos7

1. Preparation After installing the Linux operati...

HTML table tag tutorial (11): horizontal alignment attribute ALIGN

In the horizontal direction, you can set the alig...

The leftmost matching principle of MySQL database index

Table of contents 1. Joint index description 2. C...

Web page custom selection box Select

Everyone may be familiar with the select drop-dow...

How to display texture at the position of swipe in CocosCreator

Table of contents 1. Project requirements 2. Docu...

How to use Docker Compose to implement nginx load balancing

Implement Nginx load balancing based on Docker ne...

Implementation of automatic completion of Docker commands

Preface I don't know how long this friend has...

How to configure nginx+php+mysql in docker

First, understand a method: Entering a Docker con...

How to configure two-way certificate verification on nginx proxy server

Generate a certificate chain Use the script to ge...

The principles and defects of MySQL full-text indexing

MySQL full-text index is a special index that gen...

Vue custom directive details

Table of contents 1. Background 2. Local custom i...

CentOS8 - bash: garbled characters and solutions

This situation usually occurs because the Chinese...