12

Is it possible to react on URL changes in a Vue component, without including VueRouter?

In case VueRouter is present, we can watch $route, however, my application does not rely on VueRouter.

export default {
    watch: { '$route': route => console.log(window.location.href) }
}
nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • https://stackoverflow.com/questions/6390341/how-to-detect-url-change-in-javascript – Roy J Jan 19 '18 at 01:24
  • Is there any particular reason for for doing this? (I'm new to Vue, and I'm curious as to why one would want to avoid VueRouter.) – zrajm Apr 09 '19 at 09:23

1 Answers1

10

Before I used vue router, I did something like this...

data: function() {
  return {
     route: window.location.hash,
     page: 'home'
  }
},
watch: {
  route: function(){
    this.page = window.location.hash.split("#/")[1];
  }
}
retrograde
  • 2,979
  • 6
  • 28
  • 54
  • 9
    There's a [hashchange](https://developer.mozilla.org/en-US/docs/Web/Events/hashchange) event for that. Poster was looking to watch `href`, it seems. – Roy J Jan 19 '18 at 01:22