vuejs / router

🚦 The official router for Vue.js
https://router.vuejs.org/
MIT License
3.75k stars 1.15k forks source link

beforeEnter: window.history.state values are absent #2139

Closed simondrabble closed 4 months ago

simondrabble commented 4 months ago

Reproduction

https://jsfiddle.net/zcnsje7u/

Steps to reproduce the bug

  1. Click on Home in the reproduction

Expected behavior

Actual behavior

The message "bar: if you got here from home, things aren't working" is displayed.

Additional information

window.history.state is not populated with values from router.push (or router replace) in the target route's beforeEnter method. There is thus no way inside that method to redirect the user if the value is absent; while it is possible to do so outside of the navigation guard, this requires special handling inside the target component itself.

While this is a trivial example, the use of window.history.state is recommended as an approach when passing large values that do not fit comfortably in (or are otherwise inappropriate for) a query or path parameter. The inability to rely on that approach renders it all but useless.

posva commented 4 months ago

Unfortunately, this is a History API limitation, and only the current entry can be accessed. You can implement custom solutions to store your state somewhere else and pass some id as a query param like I have seen it done in other framework routers.

FYI this limitation isn't present in the still experimental Navigation API.

simondrabble commented 4 months ago

| only the current entry can be accessed

Which is what, I believe, I'm trying to do. Set state in route X, access it before route Y is entered.

posva commented 4 months ago

Oh I thought you were trying to do something else but this is still expected behavior: the state is only set after the navigation is validated, you are still in a navigation guard, the navigation can be cancelled and the state discarded.

History State is quite limited. I would recommend to only use it for data that is only needed while rendering the app (in components).

simondrabble commented 4 months ago

Ok, thanks for the response. I'll try to figure out a different approach.