Vue.js Vue Router Configuration Guide

Vue Router is the official routing manager for Vue.js, enabling us to implement Single Page Application (SPA) routing features within Vue applications. Through Vue Router, developers can map different page contents to specific URL paths, thereby achieving a seamless page switching experience without full-page refreshes. Before beginning configuration, it is essential to ensure that your project has the necessary dependencies installed.

In modern Vue projects, package management is typically handled via npm or yarn. Open your terminal and execute the following commands in the root directory of your project to install Vue Router:

npm install vue-router@latest
# Or
yarn add vue-router@latest

Upon completion of installation, you must import and instantiate the router within your main entry file (usually main.js or src/main.ts). This typically involves creating a createRouter instance and mounting it onto the Vue application.

Defining Route Configuration and Navigation Guards

The core of Vue Router lies in its route configuration object. This object defines the path mapping relationships for the application, including paths (path), components (component), and optional metadata (meta). A standard route configuration usually includes the following key attributes:

  • path: Defines the URL pattern supported by wildcards and regular expressions.
  • component: Specifies the Vue component to be rendered at that path; it can be a single component object or an array of components.
  • redirect: Used for redirection, automatically jumping from one path to another when accessing a specific route.
  • meta: Stores additional routing information, commonly used for permission control or passing extra data.

Furthermore, Vue Router provides powerful navigation guard mechanisms that allow logical checks to be executed before the user initiates a navigation action. This is typically implemented via the beforeEach hook, which handles general logic such as login status verification and authorization checks.

Here is an example of basic route configuration:

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: DashboardView,
    meta: { requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView,
    redirect: '/home'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else {
    next()
  }
})

Dynamic Routes and Parameter Passing

In practical applications, URLs often contain dynamic parameters. Vue Router supports defining dynamic path segments using the :param syntax, which can then be accessed within components via $route.params. This is crucial for building pages that require ID information, such as user details or product lists.

For example, to define a route for viewing user details:

{
  path: '/user/:id',
  name: 'user-detail',
  component: UserDetailView,
  props: true // Automatically passes parameters to component props
}

Within the UserDetailView component, you can retrieve the user ID using this.$route.params.id. If more flexible data passing is required, it can be combined with Vue 3's <script setup> syntax or state management solutions like Pinia/Vuex.

Route Switching and Navigation Methods

Vue Router offers multiple ways to trigger page transitions. The most common methods are router.push(), router.replace(), and router.go(). These allow developers to flexibly control navigation behavior within component lifecycle hooks or event handlers.

  • push: Pushes the user onto the route stack, preserving current browser history.
  • replace: Replaces the current route without adding it to the history stack.
  • go: Moves forward or backward through browsing history.

The following code example demonstrates how to navigate between pages and pass data upon button click:

import { useRouter } from 'vue-router'

const router = useRouter()

function handleLogin() {
  const userData = { name: 'Alice', age: 25 }
  router.push({
    path: '/dashboard',
    query: { user: JSON.stringify(userData) }, // Passes query parameters
    state: { from: 'login' }                   // Passes state information, supports deep nesting
  })
}

The query object allows passing simple key-value pairs of data, while the state object supports more complex structures and is suitable for carrying large amounts of context information during navigation.

Route Metadata and Custom Attributes

In addition to basic route definitions, Vue Router also supports adding custom attributes via the meta field in routes. These attributes can be accessed globally or within specific components. This feature proves highly useful for implementing Role-Based Access Control (RBAC).

Developers can define metadata such as requiresAuth and roles directly in the route configuration, then perform logical checks within navigation guards. For instance, if a user is not logged in but attempts to access an authenticated route, the system will automatically redirect them to the login page; conversely, if a user lacks sufficient permissions, they are prohibited from accessing specific pages.

Furthermore, Vue Router 3.x introduced the router-view component, responsible for rendering the currently matched route components. In Vue 3, this functionality is built directly into the <RouterView> tag, simplifying template writing processes.

By configuring route metadata and navigation logic appropriately, Vue Router helps build secure, well-structured Vue Single Page Applications with a smooth user experience.