vue全家桶进阶之路37:Vue3 路由守卫

2023-07-31,,

在 Vue.js 3.x 中,我们可以使用路由守卫来拦截路由的跳转,从而实现一些功能,例如:登录验证、页面权限控制等。

Vue.js 3.x 中的路由守卫和 Vue.js 2.x 中的基本相同,都包含了 beforeEachbeforeResolveafterEach 等钩子函数。

下面是一些常见的路由守卫用法示例:

    beforeEach

beforeEach 在跳转之前被调用,可以用来进行登录验证等操作。示例代码如下:

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: Home
},
{
path: '/user/:id',
component: User
}
]
}) router.beforeEach((to, from, next) => {
// 验证是否已登录
const loggedIn = false
if (to.path !== '/' && !loggedIn) {
next('/')
} else {
next()
}
})

在上述示例中,我们使用 beforeEach 路由守卫验证用户是否已登录,如果没有登录则跳转到首页。

    beforeResolve

beforeResolve 在跳转之前被调用,并且在 beforeEach 之后,可以用来进行一些异步操作等操作。示例代码如下:

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: Home
},
{
path: '/user/:id',
component: User,
beforeResolve: async (to, from, next) => {
// 异步操作
await someAsyncOperation() next()
}
}
]
})

在上述示例中,我们使用 beforeResolve 路由守卫进行了一些异步操作,然后在操作完成后调用了 next 方法继续跳转。

    afterEach

afterEach 在跳转完成之后被调用,可以用来进行一些页面操作等操作。示例代码如下:

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: Home
},
{
path: '/user/:id',
component: User
}
]
}) router.afterEach((to, from) => {
// 页面操作
console.log(`从 ${from.path} 跳转到 ${to.path}`)
})

在上述示例中,我们使用 afterEach 路由守卫进行了一些页面操作,例如在控制台中输出了跳转信息。

vue全家桶进阶之路37:Vue3 路由守卫的相关教程结束。

《vue全家桶进阶之路37:Vue3 路由守卫.doc》

下载本文的Word格式文档,以方便收藏与打印。