本篇文章带大家了解一下面试必问的事物---Vue-Router中的导航钩子,希望多大家有所帮助!

导航守卫
“导航”表示路由正在发生改变。
vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。【相关推荐:《vue.js教程》】
1.全局前置守卫----router.beforeEach
router.beforeEach 注册一个全局前置守卫:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// to:要去哪个页面
// from:从哪里来
// next:它是一个函数。
// 如果直接放行 next()
// 如果要跳到其它页 next(其它页)
})示例代码:
router.beforeEach(async(to, from, next) => {
NProgress.start() // 开启进度条
const token = store.state.user.token
const userId = store.state.user.userInfo.userId
console.log(token, to.path, from.path)
if (token) {
if (to.path === '/login') { // 有 token还要去login
next('/')
NProgress.done() // 关闭进度条
} else { // 有 token,去其他页面,放行
if (!userId) {
await store.dispatch('user/getUserInfo')
}
next()
}
} else {
if (to.path === '/login') { // 没有token,去login,放行
next()
} else {
next('/login') // 没有token,去其他页面
NProgress.done()
}
}
})小结
- router.beforeEach(回调(三个参数))
- 导航守卫函数中,一定要调用next( )
- to.path: to是一个路由对象,path表示路径,是它的一个属性
2. 全局后置钩子----router.afterEach
router.afterEach 注册一个全局后置钩子:
你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:
router.afterEach((to, from) => {
// ...
})3. 全局解析守卫----router.beforeResolve
在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。
4.路由独享的守卫
你可以在路由配置上直接定义 beforeEnter 守卫:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})5.组件内的守卫
beforeRouteEnterbeforeRouteUpdate(2.2 新增)beforeRouteLeave
const Foo = {
template: `...`,
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
}完整的导航解析流程
导航被触发。
在失活的组件里调用
beforeRouteLeave守卫。调用全局的
beforeEach守卫。在重用的组件里调用
beforeRouteUpdate守卫 (2.2+)。在路由配置里调用
beforeEnter。解析异步路由组件。
在被激活的组件里调用
beforeRouteEnter。调用全局的
beforeResolve守卫 (2.5+)。导航被确认。
调用全局的
afterEach钩子。触发 DOM 更新。
调用
beforeRouteEnter守卫中传给next的回调函数,创建好的组件实例会作为回调函数的参数传入。
更多编程相关知识,请访问:编程入门!!
以上就是深入浅析Vue-Router中的导航钩子的详细内容,转载自php中文网

发表评论 取消回复