解决同路由跳转报错的三种方法

这篇博客探讨了在Vue.js中如何监听并处理路由变化。通过watch选项和beforeRouteUpdate钩子函数,可以实现当路由路径改变时触发特定操作,例如更新用户信息。示例代码展示了如何在组件更新前检查新旧路由,并调用自定义方法以确保数据的同步。此外,还介绍了覆盖默认的router.push方法以捕获路由错误。
摘要由CSDN通过智能技术生成

1.watch监听$route新值和旧值是否相等

    watch:{ '$route.path':function(newValue,oldValue){ if(newValue=='xxx'){ } } }

2.利用beforeRouteUpdate钩子函数监听解决

export default{
   data(){
         return {}
  },
   beforeRouteUpdate(to,from,next){
        console.log(to,from,next)
        if(to.fullPath!=from.fullPath){
            next()
            this.changeUser()
        }
    },
    methods:{
         changeUser(){
            getUserBaseInfo({userId:this.$route.params.id}).then(res=>{
            if(res.success){
                this.stuInfo = res.data;
            }else{
                this.$message.error(res.message)
            }
            
        })
        }  
    }  
}

3.重写push方法解决(复制到main.js里面)

   import Vue from 'vue'

   import VueRouter from 'vue-router'

  const routerPush = VueRouter.prototype.push

      VueRouter.prototype.push = function push (location) {

                   return routerPush.call(this, location).catch(error => error)

                   }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值