Vue3的全局路由守卫详解
在 Vue 3 中,全局路由守卫(Global Guards)用于在导航过程中执行一些全局的逻辑,例如权限验证、页面加载前的准备工作、记录用户行为等。Vue Router 提供了三种类型的全局路由守卫:
- 全局前置守卫(Global Before Guards):在每次导航开始之前调用。
- 全局解析守卫(Global Resolve Guards):在导航被确认之前,但解析组件之后调用。
- 全局后置守卫(Global After Hooks):在导航完成后调用。
文章目录
1. 全局前置守卫(beforeEach
)
beforeEach
是最常用的全局前置守卫,它会在每次路由切换之前被调用。您可以在这个守卫中执行一些全局的逻辑,比如检查用户是否已登录、设置页面标题、记录用户访问的 URL 等。
使用方法:
import {
createRouter, createWebHistory } from 'vue-router';
import {
useAuthStore } from '@/store/auth'; // 假设您使用 Vuex 或 Pinia 进行状态管理
const router = createRouter({
history: createWebHistory(),
routes: [
// 您的路由配置
]
});
// 全局前置守卫
router.beforeEach((to, from, next) => {
const authStore = useAuthStore(); // 获取认证状态
const requiresAuth = to.matched.some(record => record.meta.requiresAuth); // 检查目标路由是否需要认证
if (requiresAuth && !authStore.isAuthenticated) {
// 如果目标路由需要认证且用户未登录,重定向到登录页面
next({
name: 'Login' });
} else {
// 否则继续导航
next();
}
});
export default router;
参数说明:
to
: 即将要进入的目标路由对象。from
: 当前导航正要离开的路由对象。next
: 必须调用此函数来解析导航。它可以接受以下参数:next()
: 继续导航。next(false)
: 中断当前的导航,停留在当前页面。next('/')
或next({ path: '/' })
: 跳转到指定的路径或路由。next(error)
: 如果传入一个Error
实例,则导航会被中断,并触发全局错误处理程序(如果有)。
2. 全局解析守卫(beforeResolve
)
beforeResolve
是在导航被确认之后