Can I handle back button within methods in vuejs 2?

If you are using vue-router(no idea if you don't, why...) a good solution is to use in your component:

  beforeRouteLeave(to, from, next) {
 if (from.name === 'nameOfFromRoute' && to.name === 'nameOfToRoute' ) {
   next(false);
 } else {
   next();
 }
 console.log({ to, from });

},


Is easy, if you need to catch that behavior only your component, you can use beforeRouteLeave function in the root of your component.

Example:

beforeRouteLeave (to, from, next) {
 const answer = window.confirm('Do you really want to leave?)
   if (answer) {
      next()
   } else {
      next(false)
   }
 }

But if you need to add this behavior globally, you need catch with beforeEnter in the routes.


If still someone come across this issue. A solution for an event listener for browser-back is https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onpopstate

window.onpopstate = function() {
  alert('browser-back');
};

Add the event on your mounted method on your root Vue component (the one the Vue instance is tied to.

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
    yourCallBackFunction () {
      // Your logic
    }
  }
  mounted () {
    document.addEventListener("backbutton", this.yourCallBackFunction, false);
  },
  beforeDestroy () {
    document.removeEventListener("backbutton", this.yourCallBackFunction);
  }
})

We also remove it on beforeDestroy to keep things tidy.

Note: I've not personally used the back button event so have added it to this example only because you say it's working but need a way to globally handle it. This code will do just that.

Note: As per @Luke's comment - we add the listener in the mounted event so it doesn't execute for in the SSR context. If SSR isn't a factor / consideration then we can use the created lifecycle hook.

Tags:

Vuejs2