vue 离开路由事件beforerouteleave 指定路由会死循环(算踩坑吧)

因为业务有需求吧。。。很久才用一次这个离开路由,呵呵了。(看来有空得看看这个beforeRouteLeave的源码讲解了)

先看下我以为的离开路由:

  beforeRouteLeave(to, from, next) {
     //console.log('to--->', to.path, this.isModify)
      if( storage.get('currentDj') && storage.get('currentDj')!='undefined' && storage.get('currentDj').id ){
            next('/in-patient-service'); //一开始这里,以为条件成立就直接跳转了。。结果死循环
      }else{
          if (this.isModify) {
            next()
          } else if (
            !this.isModify &&
            to.path !== '/in-patient-service/patient-detail'
          ) {
            next('/in-patient-service/patient-detail')
          } else {
            next()
          }
      } 
  }

为啥会死循环??????

当执行钩子函数时如果遇到next('/in-patient-service')等时会中断当前导航。

比如当前导航是去'/in-patient-service',那么遇到next('/in-patient-service')后就会把to.path改为/in-patient-service,然后会重新触发这个beforeRouteLeave离开的钩子。

注意:中断后就会改变to.path,此时会重新触发执行这个钩子,你当前的路由已经是/in-patient-service,所以才一直next('/in-patient-service') 才会死循环。

 解决办法进入条件的时候必须再重新判断下当前的to.path

所以正确的代码应该是: 

beforeRouteLeave(to, from, next) {
     //console.log('to--->', to.path, this.isModify)
      if( storage.get('currentDj') && storage.get('currentDj')!='undefined' && storage.get('currentDj').id ){
              if(to.path=='/in-patient-service'){
                  next();  //进入条件的时候必须再重新判断下当前的to.path
               }else{
                 next('/in-patient-service');
               }
      }else{
          if (this.isModify) {
            next()
          } else if (
            !this.isModify &&
            to.path !== '/in-patient-service/patient-detail'
          ) {
            next('/in-patient-service/patient-detail')
          } else {
            next()
          }
      } 
  }

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值