导航守卫(也叫路由守卫)
- 作用: — 类似 【保安】
- 导航守卫一共有三种形式
- A: 全局导航守卫
. 全局前置守卫 router.beforeEach(fn)
- fn中有三个参数
- to:表示要去哪里
- from:表示从哪里来
- next:表示通不通过
- 关于next的使用
- next() 等价于 next( true ) 表示可以从当前路由跳转到目标路由
- next( false ) 表示不通过, 表示从当前路由跳转不到目标路由
- next(’/login’) 等价于 next({path:’/login’}) 跳转指定的路由
- next(’/login’) 等价于 next({path:’/login’,params,query})
- next( fn ) 数据预载
全局前置守卫是写在入口文件 main.js 中的,在进入路由前执行
router.beforeEach( (to,from,next) =>{
const name = localStorage.getItem('name');
if( name || to.path === '/login'){
next()
}else{
next( '/login' )
}
})
router.afterEach( (to,from,next)=> {
if(to.path === '/user'){
alert('确定进入user吗')
}
})
- 全局的解析守卫
- 在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。
- 必须保证整个项目的守卫和异步路由组件解析完成
3. 全局的后置守卫 afterEach(fn)
代码在上面
B: 路由独享守卫
- 写在路由表中的守卫钩子
- 针对的是和当前路由相关的,那么其他与之不相关的路由,它是无法监听它的变化情况的
{
path: '/user',
component: User,
beforeEnter: ( to,from,next ) =>{
const name = localStorage.getItem('name');
if( name){
next()
}else{
setTimeout(()=>{
alert('你还没有登录,点击跳转登录')
next('/login')
},0)
}
}
},
C: 组件内守卫
- 有三种
- beforeRouteEnther( (to,from,next) =>{} ) 进入组件时触发【 //注意写法,fore route 】
- beforeRouteUpdate( (to,from,next) =>{} ) 数据改变时触发
- beforeRouteLeave( (to,from,next) =>{} ) 离开组件时触发
- 组件内的前置守卫 beforeRouteEnter((to,from,next)=>{})
- 导航进入组件时,调用
- this是访问不到的,如果非要访问this ,必须通过 next(vm=>{})访问
- 因为组件此时没有创建,所以没有this
- 案例: 数据预载(进入组件前就获得数据)
next(vm => {
const result = JSON.parse(res.data.slice(7,-1)).rp_result.categorys
vm.$set(vm.category,'categorys',result)
})
组件内的后置守卫
beforeRouteLeave(to,from,next){
if(this.username && this.pwd){
next()
}else{
if(confirm('你确定要离开吗')){
next()
}else{
next(false)
}
}
}
组件内的更新守卫( 路由传参和路由的接参 )
- 在当前路由改变,但是该组件被复用时调用
- 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
- 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
- 可以访问组件实例
this


