Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch route object on vue js

Tags:

vue.js

watch

How to watch route object on vue js?. 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 sanbox 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

like image 629
Komang Suryadana Avatar asked Jun 22 '18 05:06

Komang Suryadana


People also ask

How can I get route in Vuejs?

We can use this. $router. currentRoute. path property in a vue router component to get the current path.

How can I get route ID in Vuejs?

to get the value of the id route parameter with this. $route.params.id with the options API. We call useRoute to return the route object and then we get the value of the id route parameter with route.params.id .

What is router view in VUE JS?

Essentially, the router-view element gives Vue Router a location to render whatever component the current URL resolves to. For our example, we'll place it in the App. vue root component.

How do I navigate from one page to another in vue?

If you are using vue-router , you should use router.go(path) to navigate to any particular route. The router can be accessed from within a component using this. $router . Otherwise, window.


Video Answer


2 Answers

Did you try deep option?

watch: {       '$route.params.search': {         handler: function(search) {            console.log(search)         },         deep: true,         immediate: true       } } 
like image 98
ittus Avatar answered Sep 20 '22 08:09

ittus


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'); 
like image 43
santanu bera Avatar answered Sep 22 '22 08:09

santanu bera