Listening to onpopstate event on vuejs

Sunkhern picture Sunkhern · Nov 28, 2017 · Viewed 8k times · Source

I'm quite new to Vue and I'm trying to figure out how to listen to the onpopstate event on vuejs to start a specific function when it occurs. I went through the router documentation but I can't find an equivalent for the onpopstate event handler on vue.

Thanks for the help, Will

Answer

craig_h picture craig_h · Nov 28, 2017

If you're using vue-router in an SPA then I would just place it in the created hook of the base component:

  created() {
    // Attach onpopstate event handler
    window.onpopstate = function(event) {
      alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
    };
  },

Because the base component serves up all views, you should find that the event will fire throughout your entire app.

Here's the JSFiddle to show you how this setup would work: https://jsfiddle.net/bjb8ukb8/