vue-router重写push方法,解决相同路径跳转报错问题
修改vue-router的配置文件,默认位置router/index.js
importVuefrom'vue'
importRouterfrom'vue-router'
/**
*重写路由的push方法
*解决,相同路由跳转时,报错
*添加,相同路由跳转时,触发watch(针对el-menu,仅限string方式传参,形如"view?id=5")
*/
//保存原来的push函数
constrouterPush=Router.prototype.push
//重写push函数
Router.prototype.push=functionpush(location){
//这个if语句在跳转相同路径的时候,在路径末尾添加新参数(一些随机数字)
//用来触发watch
if(typeof(location)=="string"){
varSeparator="&";
if(location.indexOf('?')==-1){Separator='?';}
location=location+Separator+"random="+Math.random();
}
//这个语句用来解决报错
//调用原来的push函数,并捕获异常
returnrouterPush.call(this,location).catch(error=>error)
}
Vue.use(Router)
exportdefaultnewRouter({
routes:[
{
path:'/',
}
]
})
补充知识:vuerouter-link路径变化页面内容不变
在VUE项目中有碰到过,vue同一路由页面用router-link或者router.push()访问同一路由页面,出现url地址有变化,但是页面内容没有变化,没有重新加载信息
解决方案如下
首页