Repository navigation
Handling Stale Data When Navigating Between Routes #2772
|
Hey everyone, I have a dynamic route like this: { When I navigate from /users/1 to /users/2, Vue Router reuses the same component instance. Because of that, the old user's data can sometimes stay visible for a moment before the new data loads. What would be the recommended way to handle this? Would it be better to watch route.params.id, use onBeforeRouteUpdate(), or simply force the component to remount using a key? I'd like to know which approach is generally preferred in a real-world application. |
Replies: 1 comment
|
The usual approach is to watch const route = useRoute()
watch(
() => route.params.id,
(id) => {
fetchUser(id)
},
{ immediate: true }
)
I wouldn't force a remount with |
The usual approach is to watch
route.params.idand fetch the new data when it changes.onBeforeRouteUpdate()is also useful when you need to perform navigation-specific logic, but for simply reacting to a changed route parameter, watching the parameter is usually the cleanest option.I wouldn't force a remount with
keyunless you specifically need the component's entire state to reset.