My account

Routing in Vue

Vue Router maps URLs to components. Nested routes share a layout, lazy routes split the JavaScript so each page loads only its own code, navigation guards decide who may open a page, and the URL is the best place for state like filters. When the same component is reused for a new URL, it does not mount again, so your code must react to the param change.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleVue Router 4

Author: bezzad

Contents

The problem: four bug reports

Our shop is one Vue app. The team got four reports:

  1. The home page is slow on phones. The JavaScript file has the code of every page, even the admin panel.
  2. On a product page, “Related products” links change the URL, but the page still shows the old product.
  3. A logged-out user can open the account page for a second before it breaks.
  4. When a user shares a filtered product list, the other person sees no filters.

All four are routing problems. Let us fix them one by one.

A router maps URLs to components

import { createRouter, createWebHistory } from 'vue-router';

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: ShopLayout, // header, cart, footer
      children: [
        { path: '', component: HomePage },
        { path: 'products/:id', component: ProductPage },
        { path: 'account', component: AccountPage },
      ],
    },
  ],
});
  1. createWebHistory gives normal URLs like /products/7. The server must send index.html for every app URL, or a page refresh shows 404.
  2. Nested routes: ShopLayout has a <RouterView /> where the child page goes. The layout stays on screen and keeps its state when the user moves between child pages.
  3. Params: :id is a param. A component reads it with useRoute: route.params.id. It is always a string, so turn it into a number if you need one.
  4. Links: use <RouterLink to="/products/7">. It renders a real <a>, so the keyboard, a middle click and screen readers still work, but the click does not reload the page.

Lazy routes: load only what the page needs

{
  path: 'admin',
  component: () => import('./admin/AdminPage.vue'),
}
  1. A function with import() is a dynamic import. Vite puts that page and what it imports into its own chunk.
  2. The router loads the chunk only when the user goes to that route.
  3. Keep the home page in the main chunk, because almost every visit starts there. Make the other pages lazy, mostly the big ones like admin and checkout.
  4. Do not split into tiny pieces. Every chunk is one more request.

The same component, a new URL

/products/1/products/2click a related productThe same ProductPage: not unmounted, not mounted againonMounted onlyproduct 1still product 1watch the idproduct 1product 2
Going from product 1 to product 2 keeps the same ProductPage. onMounted does not run again, so code that loads data only on mount keeps the old product. Watch the param instead.

When the user goes from /products/1 to /products/2, both URLs use ProductPage. Vue Router reuses the component. It does not unmount and mount it again. So this code shows the old product:

const route = useRoute();
const product = ref<Product | null>(null);

onMounted(async () => {
  product.value = await getProduct(route.params.id as string);
});

Watch the param, and run once at the start with immediate:

watch(
  () => route.params.id,
  async (id) => {
    product.value = await getProduct(id as string);
  },
  { immediate: true },
);
  1. Now every param change loads the new product.
  2. If the user clicks fast, an old answer can come after a new one. Cancel the old request (AbortController) or check that the id is still the same before you save the answer.
  3. Another way is <RouterView :key="route.fullPath" />. It mounts the page again on every URL change. It is simple, but the whole page state is lost and everything renders again.
Click/accountbeforeEachneeds login? logged in?Go onAccountPage rendersRedirect/login?next=/accountStopreturn falseThe server still checks the user on every API call
Before every navigation, the router runs the guards. A guard can let the user go on, send them to another page, or stop the navigation. The page renders only after all guards say yes.
const routes = [
  {
    path: 'account',
    component: AccountPage,
    meta: { requiresAuth: true },
  },
];

router.beforeEach((to) => {
  const auth = useAuthStore();
  if (to.meta.requiresAuth && !auth.isLoggedIn) {
    return { path: '/login', query: { next: to.fullPath } };
  }
});
  1. A global beforeEach guard runs before every navigation. Return nothing (or true) to go on, return a route to redirect, or return false to stop.
  2. meta keeps extra data on a route, like “needs login”. Nested routes can check to.matched to see the meta of every parent too.
  3. The next query param lets the login page send the user back where they wanted to go. Check that it is a path in your own site, so it cannot send users to another site.
  4. A guard only protects the screen. The server must check the user on every API call, because anyone can call the API without your app.
  5. Guards can be async. A slow guard makes every click feel slow, so keep them fast.

Put shareable state in the URL

Filters, sort order, page number and search text belong in the query string. Then Back, refresh and sharing a link all work.

const route = useRoute();
const router = useRouter();

const sort = computed({
  get: () => (route.query.sort as string) ?? 'popular',
  set: (value) => router.replace({ query: { ...route.query, sort: value } }),
});
  1. replace changes the URL without a new history entry, so Back does not walk through every filter click. Use push when the change is a real new page, like a new search.
  2. Things that are not shareable, like “is this menu open”, stay in component state.

Common mistakes

Mistake Result Better way
Every page imported at the top Slow first load, mostly on phones. Lazy routes with () => import().
Loading data only in onMounted The page shows the old item after a param change. watch the param with immediate.
A guard is the only login check Anyone can still call the API. Check the user on the server too.
Plain <a> for internal links Full page reload, app state is lost. RouterLink.
Filters only in component state Back, refresh and share lose them. Query params, updated with replace.
No server fallback for history mode Refresh on /products/7 shows 404. Serve index.html for app URLs.

Summary in 6 lines

  1. Vue Router maps URLs to components. Nested routes share a layout with a RouterView.
  2. Make big pages lazy with () => import(), but do not split into tiny pieces.
  3. A param change reuses the same component, so watch the param instead of loading only on mount.
  4. Guards run before a page opens. They can go on, redirect or stop.
  5. Guards protect the screen only. The server must check every API call.
  6. Keep filters, sort and page number in the query string, so Back and sharing work.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.