v3.1.0版本里面新增功能:push和replace方法会返回一个promise,你可能在控制台看到未捕获的异常
对Router原型链上的push/replace方法进行重写,这样就不用每次调用方法都要加上catch
第一种方法:在router文件夹下的index.js中输入一下代码:
import Router from 'vue-router'
const originalPush = Router.prototype.push
Router.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)
}
第二种写法:
第一个参数:告诉原来push方法,你往哪里跳转(传递那些参数)
第二个参数:成功回调
第三个参数:失败的回调
all||apply区别
// 相同点:都可以调用函数一次,都可以篡改函数的上下文一次
// 不同点:call与apply传递参数:call传递参数用逗号隔开,apply方法执行,传递数组
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function(location, resolve, reject) {
if (resolve && reject) {
originPush.call(this, location, reject);
} else {
originPush.call(this, location, () => {}, () => {})
}
}
VueRouter.prototype.replace = function(location, resolve, reject) {
if (resolve && reject) {
originReplace.call(this, location, reject);
} else {
originReplace.call(this, location, () => {}, () => {})
}
}