Onjsdev

Share


How To Set Routes In Vue 3


By onjsdev

Dec 13th, 2023

Vue Router is a powerful routing library for Vue.js that allows you to manage your single-page application's navigation and URL structure. Here's how to set up routes in Vue 3

1. Installation

First, install the vue-router package using your preferred package manager.

For npm:

npm install vue-router

2. Create a Router Instance

In your main Vue application file (e.g., main.js), create a router instance using the createRouter function from the vue-router package.

import { createApp, createRouter, history } from 'vue-router';

const routes = [...]; // your routes array
const router = createRouter({
  history: createWebHistory(),
  routes,
});

3. Define your Routes

Create an array of route objects, where each object defines a specific route path, component, and any additional configuration.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    component: About,
  },
  // ... more routes
];

Each route object can have the following properties:

  • path: The URL path for the route.
  • name: A unique name for the route (optional).
  • component: The Vue component to render for this route.
  • props: Props to pass to the component.
  • children: An array of child routes (for nested routes).
  • redirect: Redirects the user to another route.
  • alias: An alternative path for the route.
  • beforeEnter: A navigation guard invoked before entering the route.

4. Use the Router with your App

Install the router plugin into your Vue application and provide it with the router instance you created.

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

5- Navigate between Routes

You can navigate between routes in your Vue application using the following methods:

  • router-link component: This component provides a link to navigate to a specific route.
  • router.push: This method allows programmatic navigation to a new route.
  • router.replace: This method replaces the current route with a new one.

Thank you for reading.