In this article, we will look at how to redirect to another page using the routes configuration.

For this, we make use of the redirect option and set it’s value to redirecting URL. For example,

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect: "/products",
    },
	{
        //....
    },
  ],
});

With the above configuration, a user visiting the / URL will be redirected to /products page.

Let’s implement this using a Vue app.

We will begin by creating a new application using Vue CLI.

❯ vue create redirect-routes-demo

Once, the installation is complete, we can navigate to the folder and run the server to load the application.

❯ cd redirect-routes-demo
❯ npm run serve

This will run our server on port 8080 by default http://localhost:8080/

Next, we will install the vue-router package required for routing. We can install it using CDN, npm or yarn.

npm:

npm install vue-router@4

yarn:

yarn add vue-router@4

Once the package is installed, we can integrate it with our Vue application.

In this application, we will have a “products” page that will list all the products. Let’s create the component for the same.

// Terminal
❯ touch src/components/ProductList.vue

Let’s add some code to the ProductList.vue file.

<!-- ProductList.vue -->
<template>
  <h1>Products</h1>
</template>

This component can now be imported into the main.js file.

// main.js

import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";

import ProductList from "./components/ProductList";

const app = createApp(App);

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/products",
      component: ProductList,
    },
  ],
});

app.use(router);
app.mount("#app");

Now let’s open up the URL http://localhost:8080/products in the browser.

redirect-routes-vue-1

Now let’s try to open / URL.

redirect-routes-vue-2

As you can notice, there is a warning in console - [Vue Router warn]: No match found for location with path "/". This is because we have not specified path / in our configuration.

We want to redirect to page /products whenever a user visits / page. We can do so by adding the path with redirect option.

// main.js

import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";

import ProductList from "./components/ProductList";

const app = createApp(App);

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect: "/products",
    },
    {
      path: "/products",
      component: ProductList,
    },
  ],
});

app.use(router);
app.mount("#app");

Here, we have property redirect with value /products. So, every time user tries to visit / he will be redirected to /products page.

redirect-routes-vue-1

That’s it!😃