Vue2 VueRouter 导航守卫
全局前置守卫: router.beforeEach
const router = new VueRouter({...})
router.beforeEach((to, from, next)=>{
//..
})
- to : Route, 即将要进入的目标 路由对象
- from : Route,当前导航正要离开的路由
- next : Function,一定要调用该方法来
resolve
这个钩子。执行效果依赖 next 方法的调用参数- next() : 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)
- next(false) : 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
- next('/') 或者 next({ path: '/' }) : 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
- next(error) : 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调
router.beforeEach
的作用(重要): 验证用户的身份
router.beforeEach((to, from, next)=>{
if (to.name !=='Login' && !isAuthenticated) next({name:'Login'})
else next()
})
全局解析守卫: router.beforeResolve
注册一个全局守卫,与 router.beforeEach
类似,不同的是 在导航被确认之前 , 同时当所有组件内的守卫和异步路由组件被解析之后,解析守卫被调用 。
全局后置钩子: router.afterEach
不会接受 next 函数也不会改变导航本身:
router.afterEach((to, from) =>{
//...
})
路由独享守卫(重要): beforeEnter
与全局前置守卫的方法参数是一样
const router = new VueRouter({
routes:[
{
path:'/foo',
component:Foo,
beforeEnter:(to, from, next)=>{
// ...
}
}
]
})
组件内的守卫(重要)
const Foo = {
template:`...`,
// 在渲染该组件的对应路由被 confirm 前调用
beforeRouteEnter(to, from, next){
// 不!能!获取组件实例“this”
// 因为当守卫执行前,组件实例还没有被创建
},
// 在当前 路由改变,但是该组件被复用时调用
beforeRouteUpdate(to, from, next){
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用,该钩子就在这个情况下被调用
// 可以访问组件实例 “this”
},
// 导航离开 该组件的对应路由 时调用
beforeRouteLeave(to, from, next){
// 可以访问组件实例 “this”
}
}
beforeRouteEnter
:该守卫 不能 访问 this ,可以通过传一个回调给 next 来访问组件实例。 在导航被确认的时候执行回调 ,并且把组件实例作为回调方法的参数。
beforeRouteEnter(to, from, next){
next(vm => {
// 通过”vm“ 访问组件实例
})
}
beforeRouteUpdate
: 组件复用
beforeRouteLeave
: 通常用来禁止用户在还未保存修改前突然离开
beforeRouteLeave(to, from, next){
const answer = window.confirm("还未保存,确定离开码?");
if(answer){
next()
}else{
next(false)
}
}
完整的导航解析流程
- 导航被触发
- 在失活的组件里调用
beforeRouteLeave
离开守卫 - 调用全局的
beforeEach
守卫 - 在重用的组件里调用
beforeRouteUpdate
守卫 - 在路由配置里调用
beforeEnter
- 解析异步路由组件
- 在被激活的组件里调用
beforeRouterEnter
- 调用全局的
beforeResolve
守卫 - 导航被确定
- 调用全局的
afterEach
守卫 - 触发 DOM 更新
- 用创建好的实例调用
beforeRouterEnter
守卫中传给 next 的回调函数
总结
用全局前置钩子 beforeEach
作用 验证用户身份
const router = new VueRouter({...})
router.beforeEach((to, from, next)=>{
if (to.name !=='Login' && !isAuthenticated) next({name:'Login'})
else next()
})
组件内守卫 beforeRouteLeave
通常用来 禁止用户在还未保存修改前突然离开
beforeRouteLeave(to, from, next){
const answer = window.confirm("还未保存,确定离开码?");
if(answer){
next()
}else{
next(false)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论