vue listens for route change refresh page operation in App. vue file

  • 2021-08-06 20:30:52
  • OfStack

When the route jumps, the page needs to be refreshed once again to get the data and load the page. At this time, add a listener, and refresh the page once if you jump to it.


export default {
 name: 'App',
 provide(){
 return{
  reload:this.reload
 }
 },
 data(){
 return {
  isRouterAlive:true,
 }
 },
 // Listener 
 watch: {
 //  Method 1
 '$route' (to, from) { // Listen for route changes 
  // console.log(999)
  if(to.path == "/"){ // Which page to jump to 
  location.reload()
  }
 },
 },
 methods:{
 reload(){
  this.isRouterAlive = false;
  this.$nextTick(function () {
  this.isRouterAlive = true
  });
 },
 },
}

Additional knowledge: vue listens for route changes and listens for page refresh and leave

It is necessary to distinguish the difference between the two.

First of all, listen to the refresh and leave of the page. At this time, it is equivalent to pressing refresh directly in this page. If it is webapp, it is to leave this app instead of switching routes!

If it is monitored by js, it can not only refresh and leave the page, but also switch routes. Note that when keepalive, even if the route is switched, it is invalid.

Add a listener directly to script to monitor beforeunload:


    // Monitor if the page leaves 
    created() {
      window.addEventListener('beforeunload', this.updateHandler)
    },
    beforeDestroy() {
      this.finalItemDetail(); //  What you want to do 
    },
    destroyed() {
      window.removeEventListener('beforeunload', this.updateHandler)
    },

Then add finalItemDetail and updateHandler methods to methods:


      updateHandler() {
        this.finalItemDetail()
      },
      finalItemDetail() {
        console.log(' Refresh or close ');
      },

If you want to monitor the departure of a specific page, for example, I am now under/index and now I am under/index/001, you can monitor the routing changes in watch, provided that vue-router is practical.

If it is simple to judge the route change can be commented out, directly execute the clear method (self-defined in methods)

But note that this can only listen to the changes of its own sub-routes!


    watch: {
      //  If the route changes, it will be executed again clear Method 
      // "$route": "clear",
      $route(to , from){
        console.log( to.path, from.path );
        this.clear(to.path);
      }
    },

Then I made an extra judgment:


      clear(path) {
        if(path!="/item/item01/evaluate")
          console.log(" Left from this page ");
        this. active=0;
      },

Related articles: