前言:
导航守卫主要用来通过跳转或取消的方式守卫导航
一、导航守卫的核心价值
1. 导航生命周期
- 导航被触发。
- 在失活的组件里调用
beforeRouteLeave守卫。- 调用全局的
beforeEach守卫。- 在重用的组件里调用
beforeRouteUpdate守卫(2.2+)。- 在路由配置里调用
beforeEnter。- 解析异步路由组件。
- 在被激活的组件里调用
beforeRouteEnter。- 调用全局的
beforeResolve守卫(2.5+)。- 导航被确认。
- 调用全局的
afterEach钩子。- 触发 DOM 更新。
- 调用
beforeRouteEnter守卫中传给next的回调函数,创建好的组件实例会作为回调函数的参数传入。
2. 参数与常用的方法
to:目标路由对象 (即将进入的路由),包含path、params、query等信息from:当前路由对象(即将离开的路由)next:跳转控制函数 (Vue Router 3.x 核心,Vue Router 4.x 已简化)next():放行,进入下一个守卫next(false):中断跳转,留在当前路由next('/path')或next({ path: '/path' }):跳转到指定路由(替换当前跳转)next(error):传递错误(会被router.onError捕获)
注意:Vue Router 4.x 中,next 已废弃,直接返回 true/false/ 路由对象即可。
二、导航守卫分类
1. 全局守卫(作用于所有路由)
注册在
router实例上,对所有路由跳转生效,常用场景:登录校验、权限控制、全局埋点。
(1)全局前置守卫 router.beforeEach(最常用)
路由跳转之前触发,用于拦截未登录用户、权限校验。
const router = createRouter({ ... })
router.beforeEach((to, from) => {
// ...
// 返回 false 以取消导航
return false
})
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({ history: createWebHistory(), routes })
router.beforeEach((to, from) => {
const isLogin = localStorage.getItem('token')
if (!isLogin && to.path !== '/login') {
return '/login' // 未登录,跳转到登录页
}
// 返回 true 或 undefined 表示放行
})
to: 即将要进入的目标from: 当前导航正要离开的路由
可以返回的值如下:
-
false: 取消当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到from路由对应的地址。 -
一个路由地址: 通过一个路由地址重定向到一个不同的地址,如同调用
router.push(),且可以传入诸如replace: true或name: 'home'之类的选项。它会中断当前的导航,同时用相同的from创建一个新导航。router.beforeEach(async (to, from) => {
if (
// 检查用户是否已登录
!isAuthenticated &&
// ❗️ 避免无限重定向
to.name !== 'Login'
) {
// 将用户重定向到登录页面
return { name: 'Login' }
}
})
如果遇到了意料之外的情况,可能会抛出一个 Error。这会取消导航并且调用 router.onError() 【错误处理器】注册过的回调。
如果什么都没有,undefined 或返回 true,则导航是有效的,并调用下一个导航守卫
router.beforeEach(async (to, from) => {
// canUserAccess() 返回 `true` 或 `false`
const canAccess = await canUserAccess(to)
if (!canAccess) return '/login'
})
以上所有都同 async 函数 和 Promise 工作方式一样:
router.beforeEach(async (to, from) => {
// canUserAccess() 返回 `true` 或 `false`
const canAccess = await canUserAccess(to)
if (!canAccess) return '/login'
})
确保 next 在任何给定的导航守卫中都被严格调用一次 。它可以出现多于一次,但是只能在所有的逻辑路径都不重叠的情况下,否则钩子永远都不会被解析或报错。这里有一个在用户未能验证身份时重定向到/login的错误用例:
// BAD(错误的)
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
// 如果用户未能验证身份,则 `next` 会被调用两次
next()
})
// GOOD(正确的)
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
(2)全局解析守卫 router.beforeResolve
在所有组件内守卫和路由独享守卫执行完毕后、导航确认前触发。
常用于:等待异步操作完成(如接口请求获取用户权限)后再放行。
// Vue Router 4.x 示例
router.beforeResolve(async (to, from) => {
// 异步获取用户权限
const userRole = await fetchUserRole()
// 权限不足,跳转到403
if (to.meta.requireAdmin && userRole !== 'admin') {
return '/403'
}
})
router.beforeResolve(async to => {
if (to.meta.requiresCamera) {
try {
await askForCameraPermission()
} catch (error) {
if (error instanceof NotAllowedError) {
// ... 处理错误,然后取消导航
return false
} else {
// 意料之外的错误,取消导航并把错误传给全局处理器
throw error
}
}
}
})
router.beforeResolve 是获取数据或执行任何其他操作(如果用户无法进入页面时你希望避免执行的操作)的理想位置。
(3)全局后置守卫 router.afterEach
路由跳转完成后 触发(组件已渲染),无
next参数,不能改变跳转结果。常用场景:页面标题修改、埋点统计、关闭加载状态。
router.afterEach((to, from) => {
// 修改页面标题(配合路由元信息 meta)
document.title = to.meta.title || '默认标题'
// 埋点:记录页面跳转
trackPageView(to.path)
// 关闭全局加载状态
store.commit('closeLoading')
})
router.afterEach((to, from) => {
sendToAnalytics(to.fullPath)
})
它们对于分析、更改页面标题、声明页面等辅助功能以及许多其他事情都很有用。
它们也反映了 navigation failures 作为第三个参数:
router.afterEach((to, from, failure) => {
if (!failure) sendToAnalytics(to.fullPath)
})
(4)在守卫内的全局注入
可以在导航守卫内使用 inject() 方法。这在注入像 pinia stores 这样的全局属性时很有用。在 app.provide() 中提供的所有内容都可以在 router.beforeEach()、router.beforeResolve()、router.afterEach() 内获取到:
const app = createApp(App)
app.provide('global', 'hello injections')
// router.ts or main.ts
router.beforeEach((to, from) => {
const global = inject('global') // 'hello injections'
// a pinia store
const userStore = useAuthStore()
// ...
})
2. 路由独享守卫 beforeEnter
只作用于单个路由,在路由配置中定义,优先级:全局前置守卫之后,组件内守卫之前。
const routes = [
{
path: '/profile',
component: Profile,
// 路由独享守卫
beforeEnter: (to, from, next) => { // Vue Router 3.x
const isLogin = localStorage.getItem('token')
isLogin ? next() : next('/login')
}
// Vue Router 4.x 写法
beforeEnter: (to, from) => {
const isLogin = localStorage.getItem('token')
if (!isLogin) return '/login'
}
}
]
你可以直接在路由配置上定义 beforeEnter 守卫:
const routes = [
{
path: '/users/:id',
component: UserDetails,
beforeEnter: (to, from) => {
// reject the navigation
return false
},
},
]
beforeEnter 守卫 只在进入路由时触发 ,不会在 params、query 或 hash 改变时触发。例如,从 /users/2 进入到 /users/3 或者从 /users/2#info 进入到 /users/2#projects。它们只有在 从一个不同的 路由导航时,才会被触发。
你也可以将一个函数数组传递给 beforeEnter,这在为不同的路由重用守卫时很有用:
function removeQueryParams(to) {
if (Object.keys(to.query).length)
return { path: to.path, query: {}, hash: to.hash }
}
function removeHash(to) {
if (to.hash) return { path: to.path, query: to.query, hash: '' }
}
const routes = [
{
path: '/users/:id',
component: UserDetails,
beforeEnter: [removeQueryParams, removeHash],
},
{
path: '/about',
component: UserDetails,
beforeEnter: [removeQueryParams],
},
]
当配合嵌套路由使用时,父路由和子路由都可以使用 beforeEnter。如果放在父级路由上,路由在具有相同父级的子路由之间移动时,它不会被触发。例如:
const routes = [
{
path: '/user',
beforeEnter() {
// ...
},
children: [
{ path: 'list', component: UserList },
{ path: 'details', component: UserDetails },
],
},
]
示例中的 beforeEnter 在 /user/list 和 /user/details 之间移动时不会被调用,因为它们共享相同的父级路由。如果我们直接将 beforeEnter 守卫放在 details 路由上,那么在这两个路由之间移动时就会被调用。
3. 组件内守卫(作用于当前组件)
在 Vue 组件内部定义,只对当前组件对应的路由生效,更贴近组件逻辑。
(1)beforeRouteEnter:进入组件前触发
-
此时组件实例未创建 (
this为undefined),无法访问组件内数据 / 方法。 -
若需访问组件实例,可在
<script setup> import { onMounted } from 'vue' import { useRoute } from 'vue-router'next回调中获取(Vue Router 3.x),或用onMounted(Vue Router 4.x)。const route = useRoute()
// 替代 beforeRouteEnter:组件挂载后执行
onMounted(() => {
fetchData(route.params.id)
})
</script>
(2)beforeRouteUpdate:路由参数变化时触发
组件被复用时 触发(如 /user/:id 从 id=1 跳转到 id=2),此时组件实例已存在,可访问 this。
选项式API:
export default {
beforeRouteUpdate(to, from, next) {
// to.params.id 是新参数,from.params.id 是旧参数
this.userId = to.params.id
this.fetchUserInfo(to.params.id) // 重新请求新用户数据
next() // Vue Router 3.x 需调用 next
}
}
组合式API:
<script setup>
import { watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// 监听路由参数变化
watch([() => route.params.id], (newId) => {
fetchUserInfo(newId[0])
}, { immediate: true })
</script>
(3)beforeRouteLeave:离开组件前触发
导航离开当前组件对应的路由时触发,可用于:提示未保存的表单、阻止误操作跳转。
export default {
beforeRouteLeave(to, from, next) {
// 示例:表单未保存,提示用户
if (this.formChanged) {
if (window.confirm('表单未保存,是否离开?')) {
next() // 确认离开,放行
} else {
next(false) // 取消离开,中断跳转
}
} else {
next() // 无未保存内容,直接放行
}
}
}
可用的配置 API
你可以为路由组件添加以下配置:
-
beforeRouteEnter -
beforeRouteUpdate -
<script> export default { beforeRouteEnter(to, from) { // 在渲染该组件的对应路由被验证前调用 // 不能获取组件实例 `this` ! // 因为当守卫执行时,组件实例还没被创建! }, beforeRouteUpdate(to, from) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 `/users/:id`,在 `/users/1` 和 `/users/2` 之间跳转的时候, // 由于会渲染同样的 `UserDetails` 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 因为在这种情况发生的时候,组件已经挂载好了,导航守卫可以访问组件实例 `this` }, beforeRouteLeave(to, from) { // 在导航离开渲染该组件的对应路由时调用 // 与 `beforeRouteUpdate` 一样,它可以访问组件实例 `this` }, } </script>beforeRouteLeave
beforeRouteEnter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。
不过,你可以通过传一个回调给 next 来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数:
beforeRouteEnter (to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
})
}
注意 beforeRouteEnter 是支持给 next 传递回调的唯一守卫。对于 beforeRouteUpdate 和 beforeRouteLeave 来说,this 已经可用了,所以不支持 传递回调,因为没有必要了:
beforeRouteUpdate (to, from) {
// just use `this`
this.name = to.params.name
}
这个 离开守卫 通常用来预防用户在还未保存修改前突然离开。该导航可以通过返回 false 来取消。
beforeRouteLeave (to, from) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (!answer) return false
}
使用组合 API
如果你正在使用组合式 API 编写组件,你可以通过 onBeforeRouteUpdate 和 onBeforeRouteLeave 分别添加 update 和 leave 守卫。