router icon indicating copy to clipboard operation
router copied to clipboard

Component beforeRouteUpdate not triggered after hmr

Open char101 opened this issue 6 months ago • 3 comments

Reproduction

https://github.com/char101/vue1

Steps to reproduce the bug

  1. Run pnpm run dev
  2. Click button, verify that the counter is increasing
  3. Add a comment on Test.vue to trigger hmr
  4. The button is no longer working, when clicking the button for the first time, the url is updated which implies that $router.push is working, but beforeRouteUpdate is not triggered.

Expected behavior

beforeRouteUpdate should still works after hmr.

Actual behavior

beforeRouteUpdate not called after hmr.

Additional information

No response

char101 avatar May 14 '25 06:05 char101

I guess this is because to.matched.components[0].default is a different object after hmr to from.matched.components[0].default.

I would be nice if hmr-ed components can be detected as update in the development environment.

For now I guess the workaround is to only use this.$watch.

char101 avatar May 14 '25 07:05 char101

It's indeed an HMR bug with the options API only (works with onBeforeRouteUpdate()). Contribution welcome!

posva avatar May 14 '25 09:05 posva

I can't send a pull request but I can verify that removing {flush: 'post' } in

https://github.com/vuejs/router/blob/30f8674ac4f3ee69a866bfae2280acd2a4db2daf/packages/router/src/RouterView.ts#L135

fixed the problem. The cause is that after hmr, the instances.default value in both to and from routes are null, causing the guard not to be extracted. Although the watch is triggered, it is only run later due to the flush post option.

char101 avatar May 14 '25 12:05 char101

Hi, I've reviewed the issue and the investigation from @char101 As this issue is open for contributions, I would like to take it on. I'll create a pull request based on the suggested fix.

dhyun2 avatar Aug 20 '25 01:08 dhyun2

@posva I've submitted a PR to address this issue: PR #2545 — Register view instance on mount under HMR so Options API beforeRouteUpdate works again.

Scope: Development/HMR only (production unaffected)

Fixes: Included in the description so this issue will auto-close once merged

Please let me know if any changes are needed. Thanks! 🙏

dhyun2 avatar Aug 21 '25 09:08 dhyun2