Vue implements two routing permission control methods

Vue implements two routing permission control methods

Routing permission control is often used in background management systems to restrict the permissions of pages that different business personnel can access.

For pages without permission, you can jump to the 404 page or prompt that you do not have permission.

Method 1: Routing meta information (meta)

Put all pages in the routing table and just check the role permissions when accessing them.
vue-router provides a meta configuration interface when building routes. We can add permissions corresponding to routes in the meta information, and then check the relevant permissions in the route guard to control its route jump.

In the meta attribute, add the roles that can access this route to roles. After each user logs in, the user's role is returned. Then when accessing the page, the meta attribute of the route is compared with the user's role. If the user's role is in the roles of the route, then access is allowed. If not, access is denied.

Example 1: Judging by roles

const myRouter = new VueRouter({
 routes: [{
        path: '/login',
        name: 'login',
        meta: {
         roles: ['admin', 'user']
        },
        component: () => import('@/components/Login')
    },{
        path: '/home',
        name: 'home',
        meta: {
            roles: ['admin']
        },
        component: () => import('@/views/Home')
    },{
     path: '/404',
     component: () => import('@/components/404')
   }]
})

//Assume that the user role obtained from the background through the interface can be stored in the token const role = 'user'

myRouter.beforeEach((to,from,next)=>{
 if (to.meta.roles.includes(role)) {
  next() //release }else{
  next({path:"/404"}) //jump to 404 page}
})

Example 2: Add an identifier to the meta that requires permissions

const myRouter = new VueRouter({
 routes: [{
        path: '/login',
        name: 'login',
        meta: {
         title: 'Login Page'
         icon: 'login'
        },
        component: () => import('@/components/Login')
    },{
        path: '/home',
        name: 'home',
        meta: {
         Title: 'Home'
         icon: 'home',
         requireAuth: true
        },
        component: () => import('@/views/Home')
    },{
     path: '/404',
     component: () => import('@/components/404')
   }]
})

myRouter.beforeEach((to,from,next)=>{
 let flag = to.matched.some(record=>record.meta.requireAuth);
 //Here we use the matched loop to find the reason why to.meta is not used directly:
 //When there are sub-routes, first make it clear that according to the normal click logic, the first-level route is first followed by the second-level route, and the judgment of permissions must be the same //to.meta => will directly search the meta of the sub-route. If the first-level route does not add requireAuth:true, the first-level route page should be blocked and cannot enter the second-level route page; if the user directly tampers with the URL address bar, then the second-level page can be entered, and there may be problems with permissions. Then all routes under this permission should be marked //to.matched => matched is a route array, which will collect the attributes of all routes including sub-routes, so through the loop judgment and search method, you only need to add permission identifiers to the first-level route to authorize other sub-routes under it.
 if(flag){
  next()
 }else{
  next({path:"/404"})
 }
})

Disadvantages: It is a waste of computing resources to verify each route jump. In addition, routes that users do not have access to should not be mounted in theory.

Method 2: Dynamically generate routing table (addRoutes)

By dynamically adding menus and routing tables based on user permissions or user attributes, user functions can be customized.
vue-router provides the addRoutes() method, which can dynamically register routes. It should be noted that dynamically adding routes is to push routes in the routing table. Since routes are matched in order, routes such as 404 pages need to be placed at the end of the dynamic addition.

//store.js
// Extract the routes that need to be dynamically registered into vuex const dynamicRoutes = [
  {
    path: '/manage',
    name: 'Manage',
    meta: {
      requireAuth: true
    },
    component: () => import('./views/Manage')
  },
  {
    path: '/userCenter',
    name: 'UserCenter',
    meta: {
      requireAuth: true
    },
    component: () => import('./views/UserCenter')
  }
]

Add the userRoutes array in vuex to store the user's customized menu. In setUserInfo, the user's routing table is generated according to the menu returned by the backend.

//store.js
setUserInfo (state, userInfo) {
  state.userInfo = userInfo
  state.auth = true // Mark auth as true when obtaining user information. Of course, you can also directly judge userInfo
  // Generate user routing table state.userRoutes = dynamicRoutes.filter(route => {
    return userInfo.menus.some(menu => menu.name === route.name)
  })
  router.addRoutes(state.userRoutes) // Register routes}

Modify menu rendering

// App.vue
<div id="nav">
   <router-link to="/">Home</router-link>
   <router-link to="/login">Login</router-link>
   <template v-for="(menu, index) of $store.state.userInfo.menus">
     <router-link :to="{ name: menu.name }" :key="index">{{menu.title}}</router-link>
   </template>
</div>

This is the end of this article about Vue's two ways of implementing routing permission control. For more relevant Vue routing permission control content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue routing permission control analysis
  • Vue custom instructions and dynamic routing to achieve permission control
  • How to set up Vue routing guards and page login permission control (two methods)
  • Two methods of Vue permission control (route verification)
  • Detailed explanation of vue-router routing lazy loading and permission control

<<:  Docker container custom hosts network access operation

>>:  A brief discussion on the synchronization solution between MySQL and redis cache

Recommend

MySQL 8.0.15 installation and configuration tutorial under Win10

What I have been learning recently involves knowl...

Detailed explanation of Apache website service configuration based on Linux

As an open source software, Apache is one of the ...

html page!--[if IE]...![endif]--Detailed introduction to usage

Copy code The code is as follows: <!--[if IE]&...

Use ab tool to perform API stress test on the server

Table of contents 1 A brief introduction to syste...

How to choose the format when using binlog in MySQL

Table of contents 1. Three modes of binlog 1.Stat...

jQuery implements the mouse drag image function

This example uses jQuery to implement a mouse dra...

Detailed explanation of HTML table inline format

Inline format <colgroup>...</colgroup>...

A brief discussion on the application of Html web page table structured markup

Before talking about the structural markup of web...

Detailed explanation of MySQL's Seconds_Behind_Master

Table of contents Seconds_Behind_Master Original ...

Solution for Docker container not recognizing fonts such as Songti

Problem background: When using docker to deploy t...

VMware vSphere 6.7 (ESXI 6.7) graphic installation steps

Environment: VMware VCSA 6.7 (VMware-VCSA-all-6.7...

Example of automatic stop effect after text scrolling

The effect is very simple, just copy the following...

MySQL fuzzy query usage (regular, wildcard, built-in function)

Table of contents 1. MySQL wildcard fuzzy query (...