// 重定向至具体的路由
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' },
],
});
// 重定向至命名路由
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' } },
],
});
// 重定向并带有参数
const router = new VueRouter({
routes: [
{
path: '/redirect-with-params/:id',
redirect: '/with-params/:id',
},
],
});
// 匹配所有路径并全部重定向至某个路由
const router = new VueRouter({
routes: [
{ path: '*', redirect: '/' },
// 如果将根路由命名为 index,那么还可以这样
{ path: '*', redirect: { name: 'index' } },
// 通常情况下,捕获所有路径的这种操作是在前面的所有路由都不匹配的情况下才会匹配到
// 这种路由模式一般会作为 404 not found 页面的路由,或者直接重定向至首页也可以
// 根据路由的优先级,这种 '*' 路由会放在路由配置的最后面
{ path: '*', redirect: { name: 'not-found' } },
],
});
// 可以是一个方法,动态返回重定向目标,可参照官网例子
// 根据你想要跳转的的目标路由(to)返回一个重定向路由
// 没有把重定向的目标路由写死,相当于一个路由可以重定向至多个路由
const router = new VueRouter({
routes: [
{
path: '/a',
redirect: to => {
const { hash, params, query } = to;
if (query.to === 'foo') {
return { path: '/foo', query: null };
}
if (hash === '#baz') {
return { name: 'baz', hash: '' };
}
if (params.id) {
return '/with-params/:id';
} else {
return '/bar' };
}
},
],
});
const router = new VueRouter({
routes: [
{
path: '/home', component: Home,
children: {
// absolute alias
{ path: 'foo', component: Foo, alias: '/foo' },
// relative alias (alias to /home/bar-alias)
{ path: 'bar', component: Bar, alias: 'bar-alias' },
// multiple aliases
{ path: 'baz', component: Baz, alias: ['/baz', 'baz-alias'] },
},
],
})