Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle on browser back button click event in Vuejs

Tags:

vue.js

In Vue component, I want to handle on browser back event like this:

mounted() {
  if ([browser back]) {
    console.log("browser back button clicked")
  } else {
    console.log("stay here")
  }
}

To handle browser back event, I found window.onpopstate function but I don't know how to put it inside the if statement.

Can you tell me what should I do on this case? Thank you!

like image 514
The Blues Avatar asked Sep 06 '25 03:09

The Blues


1 Answers

You don't need to put inside an if statement. The event handler is sort of an "if statement".

See this example:

mounted() {
   // if back button is pressed
   window.onpopstate = function(event) {
     alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
   };
}
like image 142
Kalimah Avatar answered Sep 08 '25 14:09

Kalimah