Home > Web Front-end > Vue.js > body text

How to implement dynamic routing and routing guards in Vue

PHPz
Release: 2023-10-15 10:36:11
Original
1126 people have browsed it

How to implement dynamic routing and routing guards in Vue

How to implement dynamic routing and routing guards in Vue

In Vue, routing is a very important concept, which is related to page jumps, permission control, etc. . This article will introduce how to implement dynamic routing and routing guards, and give specific code examples.

1. Dynamic routing

Dynamic routing refers to generating different routing configurations based on different conditions or parameters. Vue's dynamic routing is implemented using Vue Router.

  1. Install Vue Router

First, we need to install Vue Router. Run the following command in the root directory of the project:

npm install vue-router
Copy after login
  1. Configure routing file

Create a router directory in the src directory of the project, and create a index.js file, used to configure routing.

// router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: []
})
Copy after login
  1. Dynamicly generated routing

We can obtain dynamic routing configuration through the backend interface or other methods, and then add it to the routing configuration.

// router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: []
})

// 获取动态路由配置
// 假设通过接口获取到的路由数据为response.data
const dynamicRoutes = response.data

// 添加动态路由
router.addRoutes(dynamicRoutes)

export default router
Copy after login

Through the above code, we can dynamically generate routes based on the data returned by the background interface and add them to the configuration of Vue Router.

2. Route guard

Route guard can be used to control the user's permission to access a certain route. For example, the user must log in before they can access a certain page. Vue Router provides the function of route guard.

First of all, we need to understand several concepts related to route guards:

  • Global pre-guard: executed before routing switching, it can be used for global permission control and other operations. .
  • Route exclusive guard: It is only valid for a certain route and can be used for local permission control and other operations.
  • Guards within the component: Only valid for a certain component, and can be used to perform operations such as permission control within the component.
  1. Global front guard

We can use global guards in the routing configuration file (router/index.js). For example, to implement login permission control:

// router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: []
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 判断用户是否登录
  const isLogin = localStorage.getItem('isLogin')

  // 如果用户未登录,并且访问的页面需要登录权限,则跳转至登录页
  if (!isLogin && to.meta.requireAuth) {
    next('/login')
  } else {
    next()
  }
})

export default router
Copy after login

In the above code, we add global front guards through the router.beforeEach() method. In this guard, we determine whether the user is logged in and make corresponding jumps according to different situations.

  1. Route Exclusive Guard

In addition to the global front guard, we can also configure separate guards for a route. For example, to implement administrator permission control:

// router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/admin',
      component: AdminComponent,
      meta: { requireAdmin: true } // 设置路由元信息
    }
  ]
})

export default router
Copy after login
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/admin',
      component: AdminComponent,
      meta: { requireAdmin: true } // 设置路由元信息
    }
  ]
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 判断用户是否为管理员
  const isAdmin = localStorage.getItem('isAdmin')

  // 如果用户不是管理员,并且访问的页面需要管理员权限,则跳转至首页
  if (!isAdmin && to.meta.requireAdmin) {
    next('/')
  } else {
    next()
  }
})

export default router
Copy after login

In the above code, we configure the meta information meta.requireAdmin for the /admin route to specify that the page needs to be managed member permissions. Then, use the global front guard to determine whether the user is an administrator, and make the corresponding jump.

  1. Guards within components

In addition to global front guards and routing exclusive guards, Vue Router also provides guards within components. For example, to control the page scrolling behavior:

// router/index.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: []
})

export default router
Copy after login
// App.vue


Copy after login

In the above code, we use the beforeRouteUpdate() method in the App.vue component to scroll the page to the top after each route switch.

Summary: This article introduces how to implement dynamic routing and routing guards in Vue, and gives specific code examples. Dynamic routing can generate different routes by obtaining dynamic routing configuration. Route guards can be used to control users' access to a certain route, including global front guards, route exclusive guards, and guards within components. The implementation of these functions is very important for building complex front-end applications.

The above is the detailed content of How to implement dynamic routing and routing guards in Vue. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!