SyntaxStudy
Sign Up
Vue.js Setting Up Vue Router 4
Vue.js Beginner 1 min read

Setting Up Vue Router 4

Vue Router 4 is the official client-side routing library for Vue 3. Install it with `npm install vue-router@4` and create a router instance using `createRouter`. The router requires two mandatory options: `history` (created with `createWebHistory` for HTML5 pushState URLs or `createWebHashHistory` for hash-based URLs) and `routes`, an array of route records mapping URL patterns to components. Each route record requires at minimum a `path` and a `component`. Route components are typically passed as dynamic imports (`() => import(...)`) so each route chunk is loaded on demand rather than bundled into the initial JavaScript payload. This technique — route-level code splitting — dramatically reduces the time-to-interactive for large applications. After creating the router, register it with the Vue app via `app.use(router)`. Add `` to your root component where matched route components should be rendered, and use `` for declarative navigation that produces proper anchor tags without full page reloads.
Example
// src/router/index.ts
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
  },
  {
    path: '/users',
    name: 'users',
    component: () => import('../views/UsersView.vue'),
  },
  {
    path: '/users/:id',
    name: 'user-detail',
    component: () => import('../views/UserDetailView.vue'),
    props: true,          // pass :id as a prop
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('../views/NotFoundView.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition ?? { top: 0 };
  },
});

export default router;