This issue is commonly related to how Nuxt and vue-router handle dynamic route params during navigation. When you navigate programmatically (with await navigateTo() or router.push()), the route params may not be immediately available in the setup or onMounted hooks, especially if you are trying to access them synchronously right after navigation.
Key points and solutions from the knowledge sources:
- The useRoute() composable provides reactive access to route params. However, if you access useRoute().params immediately after navigation, the params might not be updated yet. This is because the navigation is asynchronous, and the component may mount before the new params are set.
- To reactively respond to changes in route params, you should use a watcher on the specific param or on the entire params object. This ensures your logic runs whenever the params change, not just on initial mount.
Example solution:
<script setup>
const route = useRoute()
watch(
() => route.params,
(newParams) => {
console.log('Route params changed:', newParams)
// Your logic here
},
{ immediate: true }
)
</script>
Or, if you want to watch a specific param (e.g., id):
<script setup>
const route = useRoute()
watch(
() => route.params.id,
(newId) => {
console.log('Route param id changed:', newId)
// Your logic here
},
{ immediate: true }
)
</script>
This approach is confirmed in the Nuxt documentation and community answers, where watchers are used to handle reactivity for route params and queries after navigation, ensuring you always get the latest values regardless of how the navigation occurred (Nuxt useRoute composable, Stack Overflow example).