Performance: Route parameters with useRoute
This affects how quickly the app can read and react to URL changes, impacting interaction responsiveness and rendering updates.
import { useRoute } from 'vue-router'; import { ref, watch } from 'vue'; export default { setup() { const route = useRoute(); const userId = ref(route.params.userId); watch(() => route.params.userId, (newId) => { userId.value = newId; }); return { userId }; } }
import { useRoute } from 'vue-router'; export default { setup() { const route = useRoute(); const userId = route.params.userId; // Using userId directly without watching route changes return { userId }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct read without watch | Minimal DOM ops | 0 reflows triggered by param read | Low paint cost but stale UI | [X] Bad |
| Reactive watch on route params | Minimal DOM ops | Reflow only on param change | Paint only on param change | [OK] Good |
useRoute function in Vue Router allow you to do inside a component?useRouteuseRoute is a Vue Router composable that provides access to the current route object inside a component.useRouteuseRoute in a Vue 3 component's setup() function?useRoute is exported from 'vue-router', so import must be from 'vue-router'.useRoute() without arguments to get the current route object./user/42 and the route is defined as /user/:id?
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
export default {
setup() {
const route = useRoute();
onMounted(() => {
console.log(route.params.id);
});
}
}/user/:id, so id is a parameter expected in route.params./user/42, so route.params.id will be "42". The console logs this value on mount.import { useRoute } from 'vue-router';
import { computed } from 'vue';
export default {
setup() {
const route = useRoute();
const userId = computed(() => route.params.id);
return { userId };
}
}
The component does not update userId when the route changes.routeroute object returned by useRoute() is reactive, but its params property is not deeply reactive by default.computed does not updateroute.params is not reactive, the computed property does not track changes, so userId stays the same.route object is not reactive, so computed won't update -> Option Aimport { useRoute } from 'vue-router';
import { computed, watch, ref } from 'vue';
export default {
setup() {
const route = useRoute();
// What should userId be?
const userId = ???
return { userId };
}
}computed(() => route.params.id) alone won't update when params change.route.fullPath to trigger updatesroute.fullPath (which is reactive) and recomputing userId ensures updates when the route changes.Pass the test and this pattern moves unknown