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

← All Vue.js Developer questions