SoFunction
Updated on 2025-04-12

Solve the issue that Vue browser back cannot trigger beforeRouteLeave

Phenomenon

When loading the first component (the first here means the first in the browser history, referred to as the component to be listened to), jumping to other pages normally can trigger beforeRouteLeave. However, pressing the browser's back button cannot listen to the event.

Solution

Currently, relatively rustic and impractical solutions are adopted. Add a layer of components, and then to the component to be listened to, so that the component to be listened to is not the first component, and can normally listen to the beforeRouteLeave event.

Note:

Because the original route was disrupted. Need to add global route listening

((to, from, next) => {
 if (to is 'Components for jumping' && from is 'Component to be listened to') {
  (-1) 
  next(false)
 } else {
  next()
 }
 // In this way, when entering the component to be listened to from a normal page A, you can enter A normally when pressing the return key in the component to be listened to.})

Summarize

The above is the problem that the editor introduced to you that Vue browser back cannot trigger beforeRouteLeave. I hope it will be helpful to everyone!