一、全局路由(两种,在man.js文件下设置)

  第一种:router.beforeEach((to,from,next)=>{})

1 router.beforeEach((to,from,next)=>{
2    if(to.path == '/login' || to.path == '/register') {
3         next();
4    } else {
5         alert('您还没有登录,请先登录');
6         next('/login');
7    }
8 })    

    #回调中的参数

     *to:进入到哪个路由去

     *from:从哪个路由来的(上一个路由)

     *next:顺延,next()——(放行)——next('/login')——(不放行),(不放行,让他跳转到login页面)--函数,决定是否展示你要看到的路由页面

  第二种:router.afterEach((to,from)=>{})

    #只有两个参数,to:进入到哪个路由去,from:从哪个路由离开

    如下,每次切换路由时,都会弹出alert,点击确定后,展示当前页面

router.afterEach((to,from)=>{
    after('after each');
})

二、路由独享守卫

  #在router文件夹下index.js文件 和path同级

beforeEnter((to,from,next)=>{
    // 里边的用法和全局一样
})

三、组件内部守卫

  #在组件.vue内部写和data()同级

  1.组件进入之前的守卫

beforeRouteEnter(to, from, next) {
    // 和全局使用一样
    // 生命周期还没开始,所以这个函数没有this
}

  2.组件更新守卫

beforeRouteUpdate(to, from, next) {
    // 和全局使用一样
    // '/:id'动态路由发生变化,页面没有重新加载,触发更新守卫
}

  3.组件离开守卫

beforeRouterLeave(to, from, next) {
    // 和全局使用一样
    // 在离开当前路由的时候触发,有this
}
posted on 2021-11-05 10:01  小丶帅  阅读(174)  评论(0编辑  收藏  举报