So, basically I'm learning Vue router and I have the following routes to navigate to the HomeView
component:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/home',
name: 'home',
component: HomeView
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
And I'm wondering if there is a better way of doing this?
CodePudding user response:
You have to add the alias
option (docs)
Example from the docs.
...
{
path: '/',
name: 'home',
component: HomeView,
alias: '/home'
},
...
From the docs:
You can even combine both and provide multiple aliases with an array:
const routes = [
{
path: '/users',
component: UsersLayout,
children: [
// this will render the UserList for these 3 URLs
// - /users
// - /users/list
// - /people
{ path: '', component: UserList, alias: ['/people', 'list'] },
],
},
]
CodePudding user response:
First of all don't use the same name for 2 different routes. There are 2 methods call Redirect and Alias: https://router.vuejs.org/guide/essentials/redirect-and-alias.html
You can check them out. In my opinion Redirect method might make your code (in this case) more readable.
Example:
const routes = [
{
path: '/',
redirect: { name: 'home' },
},
{
path: '/home',
name: 'home',
component: HomeView,
}
]