重定向
重定向的目标,可以是 path、命名路由,甚至是方法:
- 重定向到 path
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 => {
// 方法接收目标路由作为参数
// return 重定向的字符串路径/路径对象
return { path: '/search', query: { q: to.params.searchText } }
},
},
{
path: '/search',
// ...
},
]
WARNING
请注意,导航守卫 并没有应用在跳转路由上,而仅仅应用在其目标上**。在上面的例子中,在 /home
路由中添加 beforeEnter
守卫不会有任何效果。
INFO
- 在写
redirect
的时候,可以省略component
配置,因为它从来没有被直接访问过,所以没有组件要渲染 - 唯一的例外是 嵌套路由:如果一个路由记录有
children
和redirect
属性,它也应该有component
属性。
相对重定向
也可以重定向到相对位置:
js
const routes = [
{
// 将总是把/users/123/posts重定向到/users/123/profile。
path: '/users/:id/posts',
redirect: to => {
// 该函数接收目标路由作为参数
// 相对位置不以`/`开头
// 或 { path: 'profile'}
return 'profile'
},
},
]