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

Ophelia ·
更新时间:2024-09-20
· 603 次阅读

目录

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> 总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



VUE 路由

需要 登录 后方可回复, 如果你还没有账号请 注册新账号