Module: Vue Routing

Vue Router setup

Introduction

Vue Router is the official router for Vue.js. It deeply integrates with Vue's component system, allowing you to build Single Page Applications (SPAs) with a clear and maintainable structure. This guide will walk you through setting up Vue Router in your project.

Installation

First, install Vue Router using npm or yarn:

npm install vue-router@4

or

yarn add vue-router@4

Note: We're installing version 4, the latest major version. Older versions have different APIs.

Basic Setup

  1. Create a Router Instance:

    In your router directory (e.g., src/router/index.js), create a router instance:

    import { createRouter, createWebHistory } from 'vue-router';
    import HomeView from '../views/HomeView.vue'; // Import your views/components
    
    const routes = [
      {
        path: '/',
        name: 'home',
        component: HomeView
      },
      {
        path: '/about',
        name: 'about',
        // route level component
        component: () => import('../views/AboutView.vue') // Lazy loading
      }
    ];
    
    const router = createRouter({
      history: createWebHistory(process.env.BASE_URL),
      routes
    });
    
    export default router;
    
    • createRouter: Creates a new router instance.
    • createWebHistory: Creates a history mode that uses the browser's history API (clean URLs). process.env.BASE_URL is important if your app is deployed to a subdirectory.
    • routes: An array of route objects. Each object defines a mapping between a URL path and a component.
    • path: The URL path to match.
    • name: A name for the route, useful for programmatic navigation.
    • component: The component to render when the route is matched. Can be directly imported or lazy-loaded using () => import(...). Lazy loading improves initial load time.
  2. Import and Use the Router in main.js:

    In your src/main.js file, import the router and attach it to your Vue app:

    import { createApp } from 'vue';
    import App from './App.vue';
    import router from './router';
    
    const app = createApp(App);
    
    app.use(router);
    
    app.mount('#app');
    

Navigation

There are several ways to navigate between routes:

  • <router-link> Component: The preferred way for declarative navigation. It renders an <a> tag with the correct href attribute.

    <template>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </template>
    
  • Programmatic Navigation (router.push): Use this for navigation triggered by events or logic.

    import { useRouter } from 'vue-router';
    
    export default {
      setup() {
        const router = useRouter();
    
        const goToAbout = () => {
          router.push('/about');
        };
    
        return { goToAbout };
      }
    };
    
  • router.replace: Similar to router.push, but replaces the current history state instead of adding a new one. Useful for redirecting after a form submission.

  • router.go and router.back: Navigate through the browser's history.

Route Parameters

You can define dynamic segments in your routes using parameters:

const routes = [
  {
    path: '/users/:id',
    name: 'user',
    component: UserView
  }
];

Access the parameter within your component:

<template>
  <h1>User ID: {{ $route.params.id }}</h1>
</template>

<script>
export default {
  mounted() {
    console.log(this.$route.params.id); // Access the ID
  }
};
</script>

Route Query Parameters

You can also pass data through query parameters:

<router-link :to="{ path: '/search', query: { q: 'vue router' } }">Search</router-link>

Access query parameters:

<template>
  <h1>Search Query: {{ $route.query.q }}</h1>
</template>

<script>
export default {
  mounted() {
    console.log(this.$route.query.q); // Access the query parameter
  }
};
</script>

Nested Routes

Vue Router supports nested routes, allowing you to create complex application structures. This involves defining routes within routes. See the official documentation for detailed examples.

Route Meta Fields

You can add meta fields to your route definitions to store additional information about the route. This is useful for things like authentication or authorization.

const routes = [
  {
    path: '/admin',
    name: 'admin',
    component: AdminView,
    meta: { requiresAuth: true }
  }
];

History Modes

  • createWebHistory(): Uses the browser's history API (HTML5 history mode). Requires server-side configuration to handle direct links to routes.
  • createWebHashHistory(): Uses a hash symbol (#) in the URL. Works without server-side configuration but can be less aesthetically pleasing.

Resources