Detect Vue SPA url changes (listen to route updates)

Viewed 613

I have my JavaScript script injected to an existing website and running on top of it.
The website is a SPA built with Vue.js.

I would like to detect url changes (routes) in this SPA and call my own function, passing the new url as parameter.

I tried listening to the following events (based on this and this):

window.addEventListener("hashchange", myFunc);
window.addEventListener("popstate", myFunc);

but myFunc doesn't get triggered at any point.

I also tried to do this with React (using react-router) but it didn't get any route update event.
Do I have to use Vue to achieve that?

1 Answers

In vue you can use the watcher property to watch for changes in any variable and handle them. in your application including route path and route params.

watch:{
  $route: {
    handler: function(newRouteValue){
      // put your code here
    },
    deep: true
  }
}

The deep in Vue watch is to watch for deep object changes. But you can remove it, if it is not necessary.

Related