vue路由守卫
vue路由守卫分为:全局的,单个路由独享的,组件级的vue官方文档
回调函数参数
to:进入到哪个路由去,
from:从哪个路由离开,
next:函数,决定是否展示你要看到的路由页面
next({ name: ‘home’… } 或者 next({ path: ‘/’ }) 跳转一个不同的地址
next(false): 中断当前导航
全局守卫
- 全局前置守卫:router.beforeEach((to, from, next) => { })
- 全局解析守卫:router.beforeResolve((to, from, next) => { })
- 全局后置钩子:router.afterEach((to, from) => { })
1、router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。
2、注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身
组件中使用路由守卫
- beforeRouteEnter: 进入路由前的处理
- beforeRouteUpdate:$route对象发生变化
- beforeRouteLeave:离开路由前处理
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this` 使用vm
// 因为当守卫执行前,组件实例还没被创建
next(vm => {
if(from.query.isManager === '0'){
next(false)
vm.$router.replace({name: 'memberInfo', query: {agentCode:res.code,routerFrom: from.name}
}
})
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave(to,from,next){
Dialog.closeAll()
if(to.name=='policyList'){
let content ='返回后当前页面内容无法保存,确定返回吗?'
Dialog.confirm({
title: '',
content: content,
confirmText: '确定',
onConfirm: () => next(),
onCancel:()=> next(false),
})
}else{
next()
}
},
路由独享守卫
在路由中直接配置 beforeEnter
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
next({name: 'home', query: {fid:'001'}}
}
}
]
})