今天小编给大家分享一下vue跳转同一路由报错如何解决的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
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>