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

Detailed explanation of Vue project optimization and packaging

Table of contents Preface 1. Routing lazy loading...

Implementation code for adding slash to Vue element header

<template> <div class="app-containe...

How to make Python scripts run directly under Ubuntu

Let’s take the translation program as an example....

CSS3 realizes the red envelope shaking effect

There is a requirement to realize the shaking eff...

Detailed explanation of script debugging mechanism in bash

Run the script in debug mode You can run the enti...

Detailed explanation of HTML form elements (Part 2)

HTML Input Attributes The value attribute The val...

React sample code to implement automatic browser refresh

Table of contents What is front-end routing? How ...

Implementation of Docker deployment of Tomcat and Web applications

1. Download docker online yum install -y epel-rel...

Use of js optional chaining operator

Preface The optional chaining operator (?.) allow...

CSS3 uses var() and calc() functions to achieve animation effects

Preview knowledge points. Animation Frames Backgr...

A brief discussion on React native APP updates

Table of contents App Update Process Rough flow c...

Will CSS3 really replace SCSS?

When it comes to styling our web pages, we have t...

Specific use of useRef in React

I believe that people who have experience with Re...