Vue2/vue3 routing permission management method example

Vue2/vue3 routing permission management method example

1. There are generally two methods for Vue routing permission control

a. Routing meta information (meta)
b. Dynamically load menus and routes (addRoutes)

2 Routing meta information (meta) to control routing permissions

2.1 Implementation in vue2

If a website has different roles, such as administrators and ordinary users, different roles are required to have access to different pages.

At this time, we can put all the pages in the routing table and just judge the role permissions when accessing them. If you have permission, allow access. If you don't have permission, deny access and jump to the 404 page.

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.

You can add roles that can access the route to roles in the meta attribute of each route. 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.

Here is how Vue2 implements it:

import VueRouter from 'vue-router';
Vue.use(VueRouter)
...
routes: [
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: ['admin', 'user']
    },
    component: () => import('../components/Login.vue')
  },
  {
    path: 'home',
    name: 'home',
    meta: {
      roles: ['admin']
    },
    component: () => import('../views/Home.vue')
  },
]

const router = new VueRouter({
  routes
})

export default router

Introduce it in the app.vue file and register the global routing guard

//Assume there are two roles: admin and user 
//User role obtained from the background const role = 'user'
//When entering a page, the navigation guard router.beforeEach event will be triggered router.beforeEach((to,from,next)=>{
  if (to.meta.roles.includes(role)) {
   next() //release}esle{
   next({path:"/404"}) //jump to 404 page}
})

From now on, the basic routing permission control is completed

Off topic, the route guard can also solve the business demand of transferring 404 pages when the route cannot be matched, which can be achieved as follows:

import router from './router'
router.beforeEach((to, from, next) => {
   // ...
    if (to.matched.length === 0) {
        next('/404')
    } else {
        next()
    }
    //console.log(to, from, next, 'route guard')
})

2.2 Implementation in vue3

In fact, the ideas are similar, but it should be noted that the way of using routing in Vue3 is slightly different from that in Vue2. I use a simpler 404 to create a Vue3 instance. For Vue3's routing permission control, you can follow Vue2 and the following code to implement the code as follows:

Create a route:

import { createRouter, createWebHashHistory } from 'vue-router';
...
routes: [
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: ['admin', 'user']
    },
    component: () => import('../components/Login.vue')
  },
  {
    path: 'home',
    name: 'home',
    meta: {
      roles: ['admin']
    },
    component: () => import('../views/Home.vue')
  },
]
const router = createRouter({
    history: createWebHashHistory(),
    routes: routers
})
export default router;

Routing guard (globally registered in App.vue):

import {
    useRouter
} from 'vue-router';
export default {
    name: 'App',
    setup() {
        const router = useRouter();
        router.beforeEach((to, from, next) => {
            // ...
            if (to.matched.length === 0) {
                next('/404')
            } else {
                next()
            }
        })
    }
}

4. Dynamically load menus and routes (addRoutes)

Dynamically add menus and routing tables according to user permissions or user attributes to customize user functions. 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 dynamically added ones.

5. Summary

Whether it is vue2 or vue3, the implementation ideas are actually similar, but the details of using the interface will be slightly different. For us, the focus of learning must not be placed on a certain framework, but on training our own thinking.

This is the end of this article about vue2/vue3 routing permission management. For more relevant vue routing permission management 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:
  • Detailed explanation of vue3 cache page keep-alive and unified routing processing
  • Vue3.0 combined with bootstrap to create a multi-page application
  • Vue3.0 implements the encapsulation of the drop-down menu
  • Vue3+TypeScript implements a complete example of a recursive menu component
  • Detailed explanation of the difference between routing hooks in Vue2.x and Vue3.x
  • A simple example of using Vue3 routing VueRouter4
  • Use of Vue3 pages, menus, and routes

<<:  VMware virtual machine installation Linux system graphic tutorial

>>:  Tutorial on how to modify the root password in MySQL 5.7

Recommend

How to use html table (to show the visual effect of web page)

We know that when using HTML on NetEase Blog, we ...

MySQL partition table is classified by month

Table of contents Create a table View the databas...

How to use selenium+testng to realize web automation in docker

Preface After a long time of reading various mate...

Don't forget to close the HTML tag

Building web pages that comply with Web standards ...

Example code for implementing the "plus sign" effect with CSS

To achieve the plus sign effect shown below: To a...

Mysql optimization techniques for querying dates based on time

For example, to query yesterday's newly regis...

4 ways to modify MySQL root password (summary)

Method 1: Use the SET PASSWORD command First log ...

Flash embedded in web pages and IE, FF, Maxthon compatibility issues

After going through a lot of hardships, I searched...

Solution to the 404/503 problem when logging in to TeamCenter12

TeamCenter12 enters the account password and clic...

Detailed explanation of jQuery chain calls

Table of contents Chain calls A small case Chain ...