'How to handle on browser back button click event in Vuejs

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!



Solution 1:[1]

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));
   };
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin