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"),
},
],
},
];
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;
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"),
},
],
},
];
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)
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"
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
It works, thanks a lot.