DEV Community

cn-2k
cn-2k

Posted on

How to set default route in Vue.js with Vue Router!

In this article I'll teach you how to set an specific route to be default in your Vue application, this approach is more common in Dashboard Layouts, let's see.

Let's Setup!

I have an folder called /router and inside it have two files called respectively index.ts and routes.ts

routes.ts

export default [
  {
    path: "/",
    component: () => import("@/components/Layout/BaseLayout.vue"),
    children: [
      {
        path: "/customer",
        name: "Customer",
        component: () => import("@/views/Customer.vue"),
      },
    ],
  },
];
Enter fullscreen mode Exit fullscreen mode

index.ts

import { createRouter, createWebHashHistory } from 'vue-router';
import routes from './routes';

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
});

export default router;
Enter fullscreen mode Exit fullscreen mode

With this setup, the default route when user will visit the app will be '/', but this route only render the base layout from our dashboard, let see how to redirect user for another default router using redirect approach.

Using a redirect to the default route:

Add a redirect property to the router, and set it's value to the path of the default route. For example:

export default [
  {
    path: "/",
    redirect: { path: "/customer" }, // redirect property 
    component: () => import("@/components/Layout/BaseLayout.vue"),
    children: [
      {
        path: "/customer",
        name: "Customer",
        component: () => import("@/views/Customer.vue"),
      },
    ],
  },
];

Enter fullscreen mode Exit fullscreen mode

This sets the /customer route (which is mapped to the Home component) as the default, and also maps the /path to the same component via a redirect. When the user visits the website, they will be automatically redirected to the Home component.

That's all, if you have more ways to achieve this, share with us! See'ya!

Top comments (3)

Collapse
 
graceman9 profile image
Serhii Klochko

I like the way you organize routes!!

But I found that this it not work for me, but the following works. Do you know why?

redirect: `"/customer"

Collapse
 
cn-2k profile image
cn-2k • Edited

Thank you, Serhii!

I cannot find exactly where's your problem at, I maded a stackblitz for this code from the post, check if it can help you:

Code on Stackblitz

Collapse
 
falsghier profile image
Feras Alsghier 🇱🇾

It works, thanks a lot.