vue router rewrites push method to solve the problem of error reporting in the same path jump

  • 2021-08-06 20:06:22
  • OfStack

Modify vue-router configuration file, default location router/index. js


import Vue from 'vue'
import Router from 'vue-router'
 
/**
 *  Override the routed push Method 
 *  Resolve, when the same route jumps, report an error 
 *  Triggered when the same route jumps watch ( Aim at el-menu , only string The mode of transmission is like "view?id=5")
 */
 
//  Save the original push Function 
const routerPush = Router.prototype.push 
//  Rewrite push Function 
Router.prototype.push = function push(location) {
 
 //  This if Statement adds a new parameter at the end of the path when jumping to the same path ( 1 Some random numbers) 
 //  Used to trigger watch
 if(typeof(location)=="string"){
 var Separator = "&";
 if(location.indexOf('?')==-1) { Separator='?'; }
 location = location + Separator + "random=" + Math.random();
 }
 
 //  This statement is used to solve error reporting 
 //  Invoke the original push Function and catch exceptions 
 return routerPush.call(this, location).catch(error => error)
}
 
Vue.use(Router)
export default new Router({
 routes: [
 {
  path: '/',
 
 }
 ]
})

Supplementary knowledge: vue router-link path change page content remains unchanged

In the VUE project, vue and 1 routing page use router-link or router. push () to access the same 1 routing page, and url address changes, but the page content does not change, and there is no reload information

The solution is as follows


<router-link to="/home" @click.native="flushCom"> Home page </router-link>
<script>  
export default {
...
...
methods:{
 flushCom:function(){
 //router Is a routing instance , For example :var router = new Router({})
  //router.go(n) Is routed 1 A method, which means in history How many steps forward or backward in the record, 0 It means it is still current, similar to window.history.go(n)
 this.$router.go(0); 
 }
}
}
<script>  

It is equal to refreshing this page through click time after router link is triggered


Related articles: