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

How to use Navicat to operate MySQL

Table of contents Preface: 1. Introduction to Nav...

HTML 5.1 learning: 14 new features and application examples

Preface As we all know, HTML5 belongs to the Worl...

Some things to note about varchar type in Mysql

Storage rules for varchar In versions below 4.0, ...

MySQL 5.6 compressed package installation method

There are two installation methods for MySQL: msi...

Several ways to run Python programs in the Linux background

1. The first method is to use the unhup command d...

Detailed explanation of Vue3 life cycle functions and methods

1. Overview The so-called life cycle function is ...

Solution to the problem of eight hours difference in MySQL insertion time

Solve the problem of eight hours time difference ...

How to introduce Excel table plug-in into Vue

This article shares the specific code of Vue intr...

A simple example of how to implement fuzzy query in Vue

Preface The so-called fuzzy query is to provide q...

js to realize a simple puzzle game

This article shares the specific code of js to im...

The most commonly used HTML escape sequence

In HTML, <, >, &, etc. have special mean...

How to uninstall and reinstall Tomcat (with pictures and text)

Uninstall tomcat9 1. Since the installation of To...

Web Design Tutorial (3): Design Steps and Thinking

<br />Previous tutorial: Web Design Tutorial...