1:投機取巧:
在被路由導航守衛攔截后,執行代碼 console.clear(),清空控制台的報錯信息;
注意:next()方法時異步函數,需要在定時器中添加console.clear(),把這個操作添加進異步隊列
router.beforeEach((to, from, next)=>{
if(to.meta.isShow && !getToken()){
next('/login')
setTimeout('console.clear()', 300)
return
}
next()
})
解決方式二: 啰嗦式
// 使用編程式導航跳轉時,每次使用,后面都跟上.catch方法,捕獲錯誤信息 this.$router.push('/location').catch(err => ())
解決方式二: 高逼格式
- 通過重寫VueRouter原型對象上的push方法, 覆蓋原來拋出異常的方法, "吞掉"異常
/* 在創建router實例對象之前,手動覆蓋原型鏈的push來吞掉報錯catch */
// 先存儲默認底層的push
const originPush = VueRouter.prototype.push
// 覆蓋原型鏈的push
VueRouter.prototype.push = function(location,resolve,reject){
// this:路由實例對象
// 判斷用戶有沒有傳后面兩個可選參數
if( resolve || reject ){
return originPush.call(this,location,resolve,reject)
}else{// 用戶只傳了第一個參數
/*
默認底層: catch()方法代碼 throw err : 拋出異常
吞掉報錯原理: 重寫catch()方法,把默認底層的 throw err給去掉,就不會拋出異常
*/
return originPush.call(this,location).catch(err=>{
// throw err
})
}
}
const router = new VueRouter({
routes
})
