popstate
event fires again if onBeforeRouteLeave
callback returns false
#2280
Unanswered
frederikheld
asked this question in
Help and Questions
Replies: 1 comment
-
@posva Ok, if it's not a bug, what is it then? What is happening internally that is considered "expected behavior"? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Reproduction
Steps to reproduce the bug
I'm trying to catch the
popstate
event to close open modals instead of navigating to the previous view if any modals are open. While doing this, I encountered strange behavior ofonBeforeRouteLeave()
: if the callback returnsfalse
, it will make thepopstate
event fire again, but only after several milliseconds.Here's my code:
vue-router
doesn't seem to have a feature that allows to check for back button navigation. Therefore I'm listening to the event myself.If you execute the code, you will notice two things:
onBeforeRouteLeave
will fire BEFORE thepopstate
event.popstate
event will fire twice if theonBeforeRouteLeave
callback returnsfalls
but only once if it returnstrue
To work around the first issue I came up with an async solution and
setTimeout(() => {}, 0)
to put the code inside the callback at the end of the call stack. But this is not the issue here.The issue is that the return value has side-effects with
popstate
.I double-checked that it is actually the same event listener and not something from a different view. I also used
useEventListener
fromvue-use
to avoid re-registering the same callback again and again. This can't happen though, as the view is kept alive. That mentioned, removing the view from<KeepAlive>
makes no difference with this bug though.Maybe my whole approach is bonkers, but this is what I came up with through trial and error and I think that this behavior of
onBeforeRouteLeave
is wrong.Expected behavior
popstate
event should only fire once if the back button is only pressed once.Actual behavior
see above
Additional information
No response
Beta Was this translation helpful? Give feedback.
All reactions