Module: Vue Routing

Routes and views

Vue Routing: Routes and Views

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 document focuses on defining routes and associating them with views (components).

1. Defining Routes

Routes are essentially mappings between URLs and the components that should be rendered when those URLs are visited. You define these routes in a router.js (or similar named) file.

// router.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  },
  // More routes can be added here
];

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

export default router;

Explanation:

  • createRouter: This function from vue-router creates a router instance.
  • createWebHistory: This creates a history mode that uses the browser's history API (clean URLs without #). Alternatives include createWebHashHistory for URLs with a # hash.
  • routes: An array of route objects. Each object defines a single route.
  • path: The URL path that triggers this route. Can use parameters (see below).
  • name: A unique name for the route. Useful for programmatic navigation (e.g., router.push({ name: 'about' })).
  • component: The Vue component that will be rendered when the route is matched. This is your "view".

2. Views (Components)

Views are the Vue components that represent different pages or sections of your application. They are typically placed in a views directory.

Example: HomeView.vue

<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome to the home page!</p>
  </div>
</template>

<script>
export default {
  name: 'HomeView'
}
</script>

Example: AboutView.vue

<template>
  <div>
    <h1>About Page</h1>
    <p>Learn more about us.</p>
  </div>
</template>

<script>
export default {
  name: 'AboutView'
}
</script>

These are simple examples, but views can be as complex as needed.

3. Using the Router in Your App

In your main application file (e.g., main.js), you need to import the router and tell Vue to use it.

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

4. Navigation

You can navigate between routes in several ways:

  • <router-link> Component: The most common way to create links. Automatically generates <a> tags with the correct href attribute.

    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    
  • router.push() (Programmatic Navigation): Use this in your component methods to navigate based on logic.

    // In a component method
    this.router.push({ name: 'about' }); // Navigate to the 'about' route
    this.router.push('/about'); // Alternative way to navigate
    
  • router.replace(): Similar to router.push(), but replaces the current history state instead of adding a new one. Useful for redirects.

5. Route Parameters

You can define routes with parameters to create dynamic routes.

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

In this example, :id is a route parameter. You can access the value of the id parameter within your UserView component using $route.params.

Example: UserView.vue

<template>
  <div>
    <h1>User Profile</h1>
    <p>User ID: {{ userId }}</p>
  </div>
</template>

<script>
export default {
  name: 'UserView',
  computed: {
    userId() {
      return this.$route.params.id;
    }
  }
}
</script>

If you navigate to /user/123, the userId computed property will be 123.

6. Nested Routes

You can define nested routes to create more complex application structures.

// router.js
const routes = [
  {
    path: '/products',
    name: 'products',
    component: ProductsView,
    children: [
      {
        path: ':productId',
        name: 'product-detail',
        component: ProductDetailView
      }
    ]
  }
];

This defines a route for /products and a nested route for /products/:productId. The ProductDetailView will only be rendered when accessed through /products/some-product-id.

7. Route Aliases

You can define aliases for routes, allowing multiple URLs to render the same component.

// router.js
const routes = [
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/',
    name: 'root',
    component: HomeView,
    alias: '/home' // Alias for /home
  }
];

Now both / and /home will render the HomeView component. The alias property is key here.

This provides a foundational understanding of routes and views in Vue Router. For more advanced features like route guards, lazy loading, and more, refer to the official Vue Router documentation: https://router.vuejs.org/