3. Vue 编程式路由跳转多次点击报错问题

在Vue中使用编程式路由跳转时,可能会遇到多次点击导致的控制台报错问题。此问题源于Vue-router 3.0及以上版本的新特性。为解决这个问题,可以重写beforeRouteLeave和beforeRouteEnter方法,并添加异常处理来避免错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue 编程式路由跳转多次点击报错问题

  • 概述

    使用编程式路由进行跳转时,控制台报错,如下所示。

    在这里插入图片描述

  • 问题分析

    该问题存在于Vue-router v3.0之后的版本,由于新加入的同一路径跳转错误异常功能导致。

  • 解决方法

    重写 $router.push$router.replace 方法,添加异常处理。

    //push
    const VueRouterPush = VueRouter.prototype.push
    VueRouter.prototype.push = function push (to) {
      return VueRouterPush.call(this, to).catch(err => err)
    }
    
    //replace
    const VueRouterReplace = VueRouter.prototype.replace
    VueRouter.prototype.replace = function replace (to) {
      return VueRouterReplace.call(this, to).catch(err => err)
    }
    
  • 示例

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Vue 编程式路由跳转多次点击报错问题</title>
    </head>
    <body>
        <div id="app">
            <button @click="pageFirst">Page First</button>
            <button @click="pageSecond">Page Second</button>
            <router-view></router-view>
        </div> 
    
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
        <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
        <script>
            const First = { template: '<div>First Page</div>' } //调用路由name属性
            const Second = { template: '<div>Second Page</div>' }
            routes = [
                { path:'/first', name:"first" ,component: First },  //设置路由name属性
                { path: '/second', name:"second", component: Second }
            ]
            router = new VueRouter({
                routes
            })
    
            //push
            const VueRouterPush = VueRouter.prototype.push
            VueRouter.prototype.push = function push (to) {
                return VueRouterPush.call(this, to).catch(err => err)
            }
    
            //replace
            const VueRouterReplace = VueRouter.prototype.replace
            VueRouter.prototype.replace = function replace (to) {
                return VueRouterReplace.call(this, to).catch(err => err)
            }
    
            const app = new Vue({
                router,
                methods: {
                    pageFirst(){ router.push('/first') },
                    pageSecond(){ router.push({ name: 'second' }) },
                },
            }).$mount('#app')
        </script>
    </body>
    </html>
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值