Home >Web Front-end >Vue.js >How to use Vue Router to implement routing guard and permission control?

How to use Vue Router to implement routing guard and permission control?

PHPz
PHPzOriginal
2023-07-21 21:53:162072browse

How to use Vue Router to implement route guarding and permission control?

With the widespread application of Vue.js, Vue Router has become a commonly used routing manager in Vue.js development. Vue Router not only provides simple and powerful routing functions, but also implements permission control through route guards to ensure that users comply with permission rules when accessing routes. This article will introduce how to use Vue Router to implement routing guards and permission control, and provide relevant code examples.

1. Basic concepts

Before we begin, let us first understand some basic concepts.

  1. Route guard: The hook function triggered when the user routes jumps, used to control user access rights.
  2. Routing permissions: Different user roles may have different access permissions. Permission control determines which routes the user accesses based on the user role.
  3. Routing meta information (meta): Meta information can be added in the routing configuration to describe some additional information about the route, such as permission requirements, etc.

Below we will introduce how to use Vue Router to implement route guarding and permission control.

2. Routing Guards

Vue Router provides three types of routing guards:

  1. Global pre-guard (beforeEach): Triggered before route jump , often used to check whether the user is logged in and verify user permissions, etc.
  2. Global parsing guard (beforeResolve): Triggered before the routing component is parsed. It is often used in scenarios where the component is rendered asynchronously after obtaining data.
  3. Global post hook (afterEach): Triggered after routing jump, often used for operations such as counting page PV and modifying page title.

The following is a simple example that demonstrates how to use the global beforeEach guard to check whether the user is logged in:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // ... 路由配置
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查用户是否登录
  const isAuthenticated = checkAuth()

  // 如果用户已登录,允许访问
  if (isAuthenticated) {
    next()
  } else {
    // 如果用户未登录,进行跳转至登录页
    next('/login')
  }
})

In the above code, we pass beforeEach Implement global front guard. checkAuth The function is used to check whether the user is logged in. If the user is logged in, call next() to allow access to the route. If the user is not logged in, call next('/login') Jump to the login page.

3. Permission Control

In actual development, we often need to control user access to certain routes based on user roles. Vue Router provides routing meta information (meta) to meet this need.

We can add a meta attribute to each route in the routing configuration to describe the access permission requirements of the route. The following is a simple example that demonstrates how to use meta to control permissions:

const router = new VueRouter({
  routes: [
    {
      path: '/admin',
      component: Admin,
      meta: {
        requiresAuth: true, // 该路由要求用户登录
        requiresAdmin: true // 该路由要求用户具有管理员权限
      }
    },
    // ... 其他路由配置
  ]
})

Through the above configuration, we can know that accessing the /admin route requires the user to log in and have management member permissions.

Now, let’s implement a permission-controlled routing guard:

router.beforeEach((to, from, next) => {
  const isAuthenticated = checkAuth()
  const isAdmin = checkAdmin()

  // 判断是否需要登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  }
  // 判断是否需要管理员权限
  else if (to.meta.requiresAdmin && !isAdmin) {
    next('/403')
  }
  // 允许访问
  else {
    next()
  }
})

In the above code, we control user access permissions by judging the meta attribute of the route. If user login is required and the user is not logged in, jump to the login page; if administrator permissions are required and the user is not an administrator, jump to the 403 page (no permission page); otherwise, access is allowed.

Summary

This article introduces how to use Vue Router to implement routing guards and permission control. Through route guards, we can perform some operations before users access routes, such as checking user login status, verifying user permissions, etc. Through routing meta information (meta) and global pre-guards, we can implement simple and powerful permission control. I hope this article can help you better use Vue Router to implement routing guards and permission control.

The above is the detailed content of How to use Vue Router to implement routing guard and permission control?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn