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 JS ES6 coding standards

Table of contents 1. Block scope 1.1. let replace...

HTML tags: sub tag and sup tag

Today I will introduce two HTML tags that I don’t...

Detailed tutorial of pycharm and ssh remote access server docker

Background: Some experiments need to be completed...

The complete process of Docker image creation

Table of contents Preface Creation steps Create a...

Detailed explanation of Vue data proxy

Table of contents 1. What I am going to talk abou...

Solution to Incorrect string value in MySQL

Many friends will report the following error when...

Two usages of iFrame tags in HTML

I have been working on a project recently - Budou...

Use of MySQL SHOW STATUS statement

To do MySQL performance adjustment and service st...

A brief analysis of Vue's asynchronous update of DOM

Table of contents The principle of Vue asynchrono...

How to uninstall Linux's native openjdk and install sun jdk

See: https://www.jb51.net/article/112612.htm Chec...

How many times will multiple setStates in React be called?

Table of contents 1. Two setState, how many times...

HTML table tag tutorial (21): row border color attribute BORDERCOLOR

To beautify the table, you can set different bord...