在Vue3中,路由守卫的编写方式与Vue2基本一致,但需要结合Vue Router 4.x版本的使用规范。以下是详细指南:
一、路由守卫类型
1. 全局守卫
// router.js
const router = createRouter({
...})
// 全局前置守卫(每次导航前触发)
router.beforeEach((to, from, next) => {
// 必须调用next()
})
// 全局解析守卫(组件解析后触发)
router.beforeResolve((to, from) => {
// 适合处理异步数据获取
})
// 全局后置钩子(导航完成后触发)
router.afterEach((to, from) => {
// 无next参数
})
2. 路由独享守卫
const routes = [
{
path: '/admin',
component: AdminPanel,
beforeEnter: (to, from, next) => {
// 仅对该路由生效
}
}
]
3. 组件内守卫
-
选项式API:
export default { beforeRouteEnter(to, from, next) { // 不能访问this next(vm