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


 修改vue-router的配置文件,默認位置router/index.js

import Vue from 'vue'
import Router from 'vue-router'
 
 
/**
 * 重寫路由的push方法
 * 解決,相同路由跳轉時,報錯
 * 添加,相同路由跳轉時,觸發watch (針對el-menu,僅限string方式傳參,形如"view?id=5")
 */
 
// 保存原來的push函數
const routerPush = Router.prototype.push  
// 重寫push函數
Router.prototype.push = function push(location) {
 
  // 這個if語句在跳轉相同路徑的時候,在路徑末尾添加新參數(一些隨機數字)
  // 用來觸發watch
  if(typeof(location)=="string"){
    var Separator = "&";
    if(location.indexOf('?')==-1) { Separator='?'; }
    location = location + Separator + "random=" + Math.random();
  }
 
  // 這個語句用來解決報錯
  // 調用原來的push函數,並捕獲異常
  return routerPush.call(this, location).catch(error => error)
}
 
 
Vue.use(Router)
 
export default new Router({
  routes: [
    {
      path: '/',
   
    }
  ]
})

————————————————
版權聲明:本文為CSDN博主「混亂謎零」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u013595395/article/details/102912835


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM