How does routing work with Vue Router? Explain navigation guards and lazy loading.
Vue Router is the official router. It maps URLs to components and renders the match in <RouterView />; <RouterLink to="..."> navigates without reloading.
Key features
- History modes:
createWebHistory()gives clean URLs (the server must fall back toindex.htmlfor unknown paths);createWebHashHistory()uses#/and needs no server config. - Dynamic params:
/users/:id, read withuseRoute().params.id, or passed as props withprops: true. - Nested routes with
childrenand a nested<RouterView />. - Programmatic navigation:
useRouter().push({ name: 'user', params: { id } }). - Lazy loading:
component: () => import('./views/Reports.vue')creates a separate chunk per route. - Meta fields:
meta: { requiresAuth: true }for guards and titles. - Scroll behaviour: restore or reset scroll on navigation.
Navigation guards
- Global:
router.beforeEach((to, from) => ...): returnfalseto cancel, a route to redirect, or nothing to continue. Ideal for authentication. - Per-route:
beforeEnter. - In-component:
onBeforeRouteLeave(warn about unsaved changes) andonBeforeRouteUpdate(same component, new params).
Example
js
import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'home', component: () => import('@/views/Home.vue') },
{ path: '/login', name: 'login', component: () => import('@/views/Login.vue') },
{
path: '/admin',
component: () => import('@/views/AdminLayout.vue'),
meta: { requiresAuth: true, role: 'admin' },
children: [{ path: 'users/:id', name: 'admin-user', component: () => import('@/views/User.vue'), props: true }],
},
{ path: '/:pathMatch(.*)*', component: () => import('@/views/NotFound.vue') },
],
scrollBehavior: (to, from, saved) => saved ?? { top: 0 },
});
router.beforeEach(to => {
const auth = useAuthStore();
if (to.meta.requiresAuth && !auth.user) return { name: 'login', query: { redirect: to.fullPath } };
if (to.meta.role && auth.user?.role !== to.meta.role) return { name: 'home' };
});
export default router;Follow-up questions interviewers ask
Try answering each one before you open it.
Why does a component not re-fetch when only the route param changes?
Navigating from /users/1 to /users/2 reuses the same component instance, so onMounted does not run again. Watch the param (watch(() => route.params.id, load, { immediate: true })), use onBeforeRouteUpdate, or force a remount with <RouterView :key="$route.fullPath" />.