QA
Intermediate LevelVue JS

How do you handle dynamic route matching and route parameter reactivity in Vue Router?

❓ Interview Prompt: Explain dynamic route parameters (/user/:id), useRoute() hook, and watching route parameter changes.

Dynamic routes map URLs with variable segments (like '/users/42' or '/posts/tech-news') to a single component view using parameters (':id').

Accessing Route Parameters:

Use the 'useRoute()' hook in Composition API: 'const route = useRoute(); console.log(route.params.id)'.

Param Reactivity Trap:

When navigating between URLs that share the same component (from '/user/1' to '/user/2'), Vue reuses the component instance without unmounting! You must watch '() => route.params.id' to refetch data when parameters change.

Code Implementation Example

html
<script setup>
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const userData = ref(null);

async function fetchUser(id) {
  userData.value = await (await fetch(`/api/users/${id}`)).json();
}

// Watch route parameter changes when navigating between users!
watch(() => route.params.id, (newId) => {
  if (newId) fetchUser(newId);
}, { immediate: true });
</script>
💡Watching dynamic route parameter changes with useRoute().
🎯 Interview Key Takeaway

Use useRoute().params to access parameters. Watch route.params.id to handle navigation between identical route paths.

#Vue Router#Dynamic Routes#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?