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
We can use this. $router. currentRoute. path property in a vue router component to get the current path.
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 .
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.
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.
Did you try deep
option?
watch: { '$route.params.search': { handler: function(search) { console.log(search) }, deep: true, immediate: true } }
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With