广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue跳转同一路由报错的问题及解决
  • 756
分享到

vue跳转同一路由报错的问题及解决

vue跳转同一路由报错vue跳转路由报错vue跳转路由 2023-05-14 11:05:14 756人浏览 薄情痞子
摘要

目录Vue跳转同一路由报错编程式路由跳转多次点击报错问题问题分析解决方法总结vue跳转同一路由报错 vue中,如果跳转同一个页面路由,虽不会影响功能,但是会报错 原因:路由的pus

vue跳转同一路由报错

vue中,如果跳转同一个页面路由,虽不会影响功能,但是会报错

原因:路由的push会向历史记录栈中添加一个记录,同时跳转同一个路由页面,会造成一个重复的添加,导致页面的报错

解决方案:在router的index.js中重写vue的路由跳转push

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err);
}

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

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

问题分析

该问题存在于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>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: vue跳转同一路由报错的问题及解决

本文链接: https://www.lsjlt.com/news/203134.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作