Vue 路由钩子(导航守卫)详解及应用场景

全局前置守卫:beforeEach、beforeResolve、afterEach

使用场景:1.用于登录验证(及用户长时间不登录的时候,跳出是否满意)

                  3.修改title,注意1中也可以修改,但是万一不跳到下一个页面,在1中修改会出错

 

路由独享守卫:beforeEnter

                  用于需要特别处理的情况(针对beforeEach)   

const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})

              

 

组件内的守卫:beforeRouteEnter、beforeRouteUpdadte、beforeRouteLeave

注意:1.此时的this是

 

 

           2.可以通过this访问实例

           3.跳转前判断

               常用来禁止用户在还未保存修改前突然离开,该导航可以通过next( false )来取消。

            

beforeRouteLeave (to, from , next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}

posted @ 2021-10-23 12:32  果果1024  阅读(1065)  评论(0)    收藏  举报