项目场景:
在写VueCli项目,用到push时候后台红字报错,虽然问题不大,但是看着碍眼
原因分析:
找了资料,发现问题来源:
Vue-router 3.1.0 版本以上,使用 push 和 replace 进行跳转时控制台会抛出异常,例如 router.push(’/path’) 返回了 promise ,之前的版本没有报错是因为 vue-router 根本没有返回错误信息,所以之前我们一直无法捕获异常。
解决:
方法一
使用的时候用错误拦截
router.push('/path').catch(err => {})
方法二
全局进行错误拦截:
const routerMethods = ['push', 'replace']
routerMethods.forEach(method => {
const originalCall = VueRouter.prototype[method]
VueRouter.prototype[method] = function(location, onResolve, onReject) {
if (onResolve || onReject) {
return originalCall.call(this, location, onResolve, onReject)
}
return originalCall.call(this, location).catch(err => err)
}
})
方法三
changeOrigin参数,接收一个布尔值,如果设置为true,那么本地会虚拟一个服务端接收你的请求并代你发送该请求,这样就不会有跨域问题了,当然这只适用于开发环境
在vue.config.js里面做配置
proxy: {
// 这是开发环境
'^/api': {
target: 'http://kumanxuan1.f3322.net:8084',
// target:'http://www.520it.com:8084'
// 重写路径 把'/api' 换成空字符创
pathRewrite: { '/api': '' },
changeOrigin:true //解决路跳转后台报错
}
}
方法四
直接改用Vue-router 3.1.0 以前的版本
npm i vue-router@3.0 -S
版权声明:本文为weixin_46736220原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。