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>