1.简单介绍
导航守卫主要用来通过跳转或取消的方式守卫导航(导航表示路由正在发生改变),当需要在路由跳转前做一些验证(登录验证)时,就需要使用vue-router 导航守卫
2.全局前置导航守卫 router.beforeEach
const router=new vueRouter({
routes:[
{
path:'/foo',
component:Foo,
meta:{
auth:true
},
children:[{
path:'bar',
component:Bar
}]
}
]
})
router.beforeEach((to,from,next)=>{
if(to.matched.some(val=>val.meta.auth)){
next('/login?returnUrl='+to.path) //跳转至该路由并传参url
}else{
next() 一定要调用next(),来执行下一步操作
}
})
导航守卫方法接收三个参数
- to:即将要进入的目标路由对象
- from:当前要离开的路由对象
- next: 是一个函数,执行效果依赖next方法的调用参数
- next()进入管道中的下一个钩子
- next(false)中断当前的导航
- next(‘/‘)跳转到不同的地址(括号中为要跳的路由地址)
3.组件内的守卫
@click="$router.push({ name: 'address', params: { city}})"
beforeRouteEnter (to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
vm.city=to.params.city
})
}