Komang Suryadana
Komang Suryadana

Reputation: 696

Watch route object in VueJS 2

How to watch route object on VueJS 2?. This is my code

watch: { 
  '$route.params.search': function(search) {
    console.log(search)
  }
}

It doesn't work.

I try use with deep still not working on here

Look on code sandbox you can watch route object on main.js.

You should not watch for the route object inside any other components. Because components get destroyed when router link changes. You should do it in the main.js file, according to your directory structure

Thanks @santanu and @ittus

Upvotes: 48

Views: 107920

Answers (4)

Sweet Chilly Philly
Sweet Chilly Philly

Reputation: 3219

I was having trouble with reactivity dynamically changing route with a router-link.

The issue was the route will change but my siteData fetched from a method returned by data() was not:

I had to watch the route like so:

    watch: {
      '$route' (to, from) {
        if(to !== from ) {
          this.siteData = this.getSiteData();
        }
      }
    },

Hope this helps others with this problem

Upvotes: 8

santanu bera
santanu bera

Reputation: 1311

In my code i did like the following -

watch:{
  '$route' (to, from){
    // Put your logic here...
  }
},

Don't watch for the $route object inside any other components. Because as the router link changes the component gets destroyed and new component is being mounted. So the watchers for the component gets destroyed. Watch for the $route object inside the root Vue instance where you inject the router object. like the following --

const app = new Vue({
  router,
  watch: {
    '$route' (to, from){
      // Code
    }
  }
}).$mount('#element');

Upvotes: 35

ittus
ittus

Reputation: 22403

Did you try deep option?

watch: { 
  '$route.params.search': {
    handler: function(search) {
      console.log(search)
    },
    deep: true,
    immediate: true
  }
}

Upvotes: 68

Nuno Ribeiro
Nuno Ribeiro

Reputation: 2565

Simple use:

watch: {
    "$route.params.search"(value) {
      //Your code here
    }
  }

Upvotes: 13

Related Questions