“导航”,表示路由正在发生改变。vue-router
提供的导航守卫主要用来通过跳转或取消的方式守卫导航。主要用于在导航过程中重定向和取消路由,或者添加权限验证、数据获取等业务逻辑。
**分类:**全局守卫,路由独享的守卫、组件内守卫,可以用在路由导航过程中的不同阶段。
**参数:**每个导航守卫都有两个参数,to 和 from,表示“到哪里去”和“从哪里来。
全局守卫分为全局前置守卫、全局解析守卫和全局后置钩子。
当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve (解析)完之前一直处于 等待中(挂起状态)。全局前置守卫使用 router.beforeEach()
注册,示例代码如下:
const router = createRouter({ ... })
router.beforeEach((to, from) => {
// ...
// 返回 false 以取消导航
return false
})
每个守卫方法接收两个参数:
可以返回的值如下:
false
: 取消当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from
路由对应的地址。router.push()
一样,你可以设置诸如 replace: true
或 name: 'home'
之类的配置。当前的导航被中断,然后进行一个新的导航,就和 from
一样。如果遇到了意料之外的情况,可能会抛出一个 Error
。这会取消导航并且调用 router.onError()
注册过的回调。
如果什么都没有,undefined
或返回 true
,则导航是有效的,并调用下一个导航守卫
以上所有都同 async
函数 和 Promise 工作方式一样:
router.beforeEach(async (to, from) => {
// canUserAccess() 返回 `true` 或 `false`
return await canUserAccess(to)
})
可选的第三个参数 next
在之前的 Vue Router 版本中,也是可以使用 第三个参数 next
的。这是一个常见的错误来源,可以通过 RFC 来消除错误。然而,它仍然是被支持的,这意味着你可以向任何导航守卫传递第三个参数。在这种情况下,确保 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()
})
你可以用 router.beforeResolve
注册一个全局守卫。这和 router.beforeEach
类似,因为它在 每次导航时都会触发,但是确保在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被正确调用。这里有一个例子,确保用户可以访问自定义 meta 属性 requiresCamera
的路由:
router.beforeResolve
是一个理想的位置,可以在用户无法进入页面的情况下,获取数据或进行任何其他你想避免的操作。
router.beforeResolve(async to => {
if (to.meta.requiresCamera) {
try {
await askForCameraPermission()
} catch (error) {
if (error instanceof NotAllowedError) {
// ... 处理错误,然后取消导航
return false
} else {
// 意料之外的错误,取消导航并把错误传给全局处理器
throw error
}
}
}
})
全局后置钩子使用 router.afterEach()
注册,和守卫不同的是,这些钩子不会接受 next
函数也不会改变导航本身。
router.afterEach((to, from) => {
sendToAnalytics(to.fullPath)
})
它们对于分析、更改页面标题、声明页面等辅助功能以及许多其他事情都很有用。
全局后置钩子可以接受一个表示导航失败的 failure 参数,作为其第三个参数,代码如下:
router.afterEach((to, from, failure) => {
if (!failure) sendToAnalytics(to.fullPath)
})
<template>
<div>
用户名:<input type="text" v-model.trim="obj.username" />
密码:<input type="password" v-model.trim="obj.password" />
<button @click="login">登录</button>
<span>{{ obj.info }}</span>
</div>
</template>
<script>
import { reactive } from '@vue/reactivity'
import { useRoute, useRouter } from 'vue-router'
export default {
setup () {
const obj = reactive({
username: 'zibo',
password: '123',
info: '' // 用于保存登陆失败之后的提示信息
})
// 拿到 route,注意这两行代码需要在 setup 函数下调用,不可在方法中调用,否则返回空
const route = useRoute()
const router = useRouter()
// 登录方法
const login = () => {
// 在实际场景中使用 Ajax 来请求服务器的数据,以进行验证
if (obj.username === 'zibo' && obj.password === '123') {
// 账号密码验证通过
sessionStorage.setItem('isAuth', true)
obj.info = ''
// 如果存在查询参数(就是说用户打算访问某页面,在登录完成之后跳转到他想访问的页面)
console.log(route)
if (route.query.redirect) {
const redirect = route.query.redirect
// 跳转到登录前想要访问的页面
router.replace(redirect)
} else {
// 跳到首页
router.replace('/')
}
} else {
// 密码错误
sessionStorage.setItem('isAuth', false)
obj.username = ''
obj.password = ''
obj.info = '账号或密码错误!'
}
}
return { obj, login }
}
}
</script>
<style>
</style>
这里仅贴出相关代码
import Login from '../views/Login.vue'
...
// 配置在一级导航里面
const routes = [
...
{
path: '/login',
name: 'login',
component: Login
}
...
]
...
// 全局前置守卫
router.beforeEach(to => {
// 判断目标路由是否为 login ,如果是就不同验证权限(直接返回 true ),反之验证权限
if (to.path === '/login') {
return true
} else {
// 判断用户是否已经登录,注意这里是对字符串进行判断
if (sessionStorage.isAuth === 'true') {
return true
} else {
return {
path: '/login',
query: { redirect: to.fullPath }
}
}
}
})
...
前面,我们进行怎样的路由跳转,页面的标题都没有任何变化,那是因为我们写的是单页面应用,本来就在一个页面里面进行的“跳转”,但这样看起来好像不太对劲,我们可以在路由导航配置文件 index.js 中添加 meta 字段并在全局后置钩子里面修改页面 title 实现目的!
import { createRouter, createWebHashHistory } from 'vue-router'
import Study from '../views/Study.vue'
import Home from '../views/Home.vue'
import News from '../views/News.vue'
import One from '../views/One.vue'
import Two from '../views/Two.vue'
import Books from '../views/Books.vue'
import Videos from '../views/Videos.vue'
import Book from '../views/Book.vue'
import Message from '../views/Message.vue'
import Login from '../views/Login.vue'
const routes = [
{
path: '/',
component: Study,
name: 'study',
redirect: '/home',
meta: {
title: '主页'
},
children: [
{
path: '/home',
name: 'home',
component: Home,
meta: {
title: '主页'
}
}, {
path: '/news',
name: 'news',
component: News,
// redirect: '/news/test', // 可以直接重定向,就显示了 /news/test
children: [
{
path: 'test',
components: {
one: One,
two: Two
}
}
],
meta: {
title: '新闻'
}
}, {
path: '/books',
name: 'books',
component: Books,
children: [
{ path: '/book/:id', name: 'book', component: Book }
],
meta: {
title: '图书'
}
}, {
path: '/videos',
name: 'videos',
component: Videos,
meta: {
title: '视频'
}
}, {
path: '/message',
name: 'message',
component: Message,
props: route => ({ query: route.query.q }),
meta: {
title: '消息'
}
}
]
}, {
path: '/login',
name: 'login',
component: Login,
meta: {
title: '登录'
}
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
// 全局前置守卫
router.beforeEach(to => {
// 判断目标路由是否为 login ,如果是就不同验证权限(直接返回 true ),反之验证权限
if (to.path === '/login') {
return true
} else {
// 判断用户是否已经登录,注意这里是对字符串进行判断
if (sessionStorage.isAuth === 'true') {
return true
} else {
return {
path: '/login',
query: { redirect: to.fullPath }
}
}
}
})
// 全局后置钩子
router.afterEach(to => {
// 这行代码写在全局前置守卫会更快
document.title = to.meta.title
})
export default router
作用:指定受保护的页面,当访问受保护页面时才进行登陆验证;
下面仅贴出变动的代码
{
path: '/videos',
name: 'videos',
component: Videos,
meta: {
title: '视频',
// 设置需要登录验证才能访问本页面
requiresAuth: true
}
}
// 全局前置守卫
router.beforeEach(to => {
// 判断该路由是否需要权限
if (to.matched.some(record => record.meta.requiresAuth)) {
// 路由需要验证,判断是否需要登录
if (sessionStorage.isAuth === 'true') {
return true
} else {
return {
path: '/login',
query: { redirect: to.fullPath }
}
}
} else {
return true
}
})
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rcdSx1tu-1641036776547)(image-20210622211054453.png)]
路由独享的守卫是在配置路由对象的时候直接定义的 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],
},
]
请注意,你也可以通过使用路径 meta 字段和全局导航守卫来实现类似的行为。
可以在路由组件内直接定义路由导航守卫(传递给路由配置的)
你可以为路由组件添加以下配置:
beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave
const UserDetails = {
template: `...`,
beforeRouteEnter(to, from) {
// 在渲染该组件的对应路由被验证前调用
// 不能获取组件实例 `this` !
// 因为当守卫执行时,组件实例还没被创建!
},
beforeRouteUpdate(to, from) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 `/users/:id`,在 `/users/1` 和 `/users/2` 之间跳转的时候,
// 由于会渲染同样的 `UserDetails` 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 因为在这种情况发生的时候,组件已经挂载好了,导航守卫可以访问组件实例 `this`
},
beforeRouteLeave(to, from) {
// 在导航离开渲染该组件的对应路由时调用
// 与 `beforeRouteUpdate` 一样,它可以访问组件实例 `this`
},
}
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 和 setup
函数来编写组件,你可以通过 onBeforeRouteUpdate
和 onBeforeRouteLeave
分别添加 update 和 leave 守卫。 请参考组合 API 部分以获得更多细节。
beforeRouteLeave
守卫。beforeEach
守卫。beforeRouteUpdate
守卫(2.2+)。beforeEnter
。beforeRouteEnter
。beforeResolve
守卫(2.5+)。afterEach
钩子。beforeRouteEnter
守卫中传给 next
的回调函数,创建好的组件实例会作为回调函数的参数传入。