vue-router重寫push方法,解決相同路徑跳轉報錯

在router的index.js里面寫,在use之前,如果加上以下代碼,報錯‘Cannot read properties of undefined (reading ‘catch’) at VueRouter.push ’那就是vue-router的版本問題,安裝高一點的版本即可3.1.6以上

// 保存原來的push函數
const originalPush = Router.prototype.push;
// 重寫push函數
Router.prototype.push = function push(location) {
  // return originalPush.call(this, location).catch(err => err);

  // 這個if語句在跳轉相同路徑的時候,在路徑末尾添加新參數(一些隨機數字)
  // 用來觸發watch
  if(typeof(location)=="string"){
    var Separator = "&";
    if(location.indexOf('?')==-1) { Separator='?'; }
    location = location + Separator + "random=" + Math.random();
  }
 
  // 這個語句用來解決報錯
  // 調用原來的push函數,并捕獲異常
  return originalPush.call(this, location).catch(error => error);
};
Vue.use(Router);
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容