发布时间:2025-12-09 13:53:36 浏览次数:3
使用vue 3.0 写了一个登入页面,再点击登入的时候,第一次点击会没有反应,F12查看接口都调用了但是没有跳转,控制台打印出错:
错误说有异常没有捕获;
这个错误是vue -router 内部的错误,没有进行catch处理导致的;
再vue-router3.0以上的版本新增功能:push和replace方法会返回一个promise;
解决方案:
在vue的router的js中添加下面代码
const originalPush = VueRouter.prototype.pushconst originalReplace = VueRouter.prototype.replace// pushVueRouter.prototype.push = function push (location, onResolve, onReject) { if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject) return originalPush.call(this, location).catch(err => err)}// replaceVueRouter.prototype.replace = function push (location, onResolve, onReject) { if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject) return originalReplace.call(this, location).catch(err => err)}其中VueRouter是在vue初始化的时候引入的Router,完整代码:router/index.js
import VueRouter from 'vue-router'Vue.use(VueRouter);// 解决报错const originalPush = VueRouter.prototype.pushconst originalReplace = VueRouter.prototype.replace// pushVueRouter.prototype.push = function push (location, onResolve, onReject) { console.log(onReject + onResolve) // if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject) return originalPush.call(this, location).catch(err => { console.log(err) originalPush.call(this, location, onResolve, onReject) });}// replaceVueRouter.prototype.replace = function push (location, onResolve, onReject) { console.log(onReject + onResolve) // if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject) return originalReplace.call(this, location).catch(err => { console.log(err) originalPush.call(this, location, onResolve, onReject) })}.......const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes})