beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave的使用

参考资料:vue-router

1、beforeRouteEnter的使用场景:组件复用;路由跳转

beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    console.log(to)
    console.log(from)
    console.log(next)
    next(vm => {
      console.log(vm)
    })
}

 使用案例:校验用户是否登录:

beforeRouteEnter: (to, from, next) => {
    let user_info = Storage.get(G.storage_key);
    if (to && to.path !== "/login") {
        if (_.isEmpty(user_info)) {
            logout();
        } else {
            next();
        }
    } else if (to && to.path === G.loginPage) {
        if (!_.isEmpty(user_info)) {
            next(".hme/);
        } else {
            next();
        }
    }
},

2、beforeRouteUpdate

beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    // 别忘了调用next
 }

使用案例:

beforeRouteUpdate(to, from, next) {
      var isNeedRedirect = this.isNeedRedirect(to.path);
      if (isNeedRedirect) {
        next({name: '_404'});
      } else {
        next();
      }
      next();
    },

 

3、beforeRouteLeave

 beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值