重定向和别名
重定向
重定向也在 routes 配置中完成。要从 /home 重定向到 /
js
const routes = [{ path: '/home', redirect: '/' }]重定向也可以指向命名路由
js
const routes = [{ path: '/home', redirect: { name: 'homepage' } }]甚至可以使用函数进行动态重定向
js
const routes = [
{
// /search/screens -> /search?q=screens
path: '/search/:searchText',
redirect: to => {
// the function receives the target route as the argument
// we return a redirect path/location here.
return { path: '/search', query: { q: to.params.searchText } }
},
},
{
path: '/search',
// ...
},
]请注意,导航守卫 不会应用于重定向的路由,而只应用于其目标。例如,在上面的示例中,向 /home 路由添加 beforeEnter 守卫将没有任何效果。
在编写 redirect 时,可以省略 component 选项,因为它永远不会被直接访问,因此没有组件要渲染。唯一的例外是 嵌套路由:如果路由记录具有 children 和 redirect 属性,则它也应该具有 component 属性。
相对重定向
也可以重定向到相对位置
js
const routes = [
{
// will always redirect /users/123/posts to /users/123/profile
path: '/users/:id/posts',
redirect: to => {
// the function receives the target route as the argument
// a relative location doesn't start with `/`
// or { path: 'profile'}
return 'profile'
},
},
]别名
重定向意味着当用户访问 /home 时,URL 将被替换为 /,然后匹配为 /。但是什么是别名呢?
/ 的别名为 /home 意味着当用户访问 /home 时,URL 保持为 /home,但它将被匹配,就好像用户正在访问 / 一样。
以上可以在路由配置中表示为
js
const routes = [{ path: '/', component: Homepage, alias: '/home' }]别名使您可以自由地将 UI 结构映射到任意 URL,而不是受配置的嵌套结构的限制。使别名以 / 开头,以在嵌套路由中使路径绝对。您甚至可以将两者结合起来,并使用数组提供多个别名
js
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'] },
],
},
]如果您的路由具有参数,请确保在任何绝对别名中都包含它们
js
const routes = [
{
path: '/users/:id',
component: UsersByIdLayout,
children: [
// this will render the UserDetails for these 3 URLs
// - /users/24
// - /users/24/profile
// - /24
{ path: 'profile', component: UserDetails, alias: ['/:id', ''] },
],
},
]关于 SEO 的说明:在使用别名时,请确保 定义规范链接。