Vue.js Developer interview question · Most asked
How do you use Vue Router: dynamic routes, nested routes and navigation guards?
Summary
Routes map paths to components; dynamic segments (/users/:id) become route.params; nested routes render children inside a parent's <RouterView>; navigation guards (router.beforeEach, per-route beforeEnter, in-component onBeforeRouteLeave) can redirect or cancel navigation, for example for authentication or unsaved changes.
Longer Answer
router.beforeEach((to) => {
const auth = useAuthStore();
if (to.meta.requiresAuth && !auth.isLoggedIn) {
return { name: "login", query: { redirect: to.fullPath } };
}
});
In Vue Router 4, guards return false to cancel, a route location to redirect, or nothing to continue; the next callback is optional. When only params change (/users/1 to /users/2) the same component instance is reused, so watch route.params (or use a key on <RouterView>) to reload data. Client-side guards are for user experience; the server must still authorise every API call.
Key Points
- Dynamic params, nested routes.
- Guards return false / location / nothing.
- Same component reused on param change.
- Guards are UX; the API must authorise.
Deep dive: Request Lifecycle course: The Browser Side: React and Vue Page Loads
More most-asked Vue.js Developer questions
- Options API or Composition API: what is the difference, and which would you use?
- What are composables, and why did they replace mixins?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- Why does v-for need a key, and why should it not be the index?
- How do props work, and what is one-way data flow?
- Pinia or Vuex: what is the difference, and why is Pinia now recommended?