当用户访问/a时,URL将会被替换成/b,然后匹配路由为/b
重定向也是通过routes配置来完成,下面例子是从/a重定向到/b:
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/`b` }
]
})
重定向的目标也可以是一个命名的路由:
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})
甚至是一个方法,动态返回重定向目标:
const rouer = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接受 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})
例子:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const Home = { template: ' ' }
const Default = { template: 'default' }
const Foo = { template: 'foo' }
const Bar = { template: 'bar' }
const Baz = { template: 'baz' }
const WithParams = { template: '{{ $route.params.id }}' }
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: Home,
children: [
{ path: '', component: Default },
{ path: 'foo', component: Foo },
{ path: 'bar', component: Bar },
{ path: 'baz', name: 'baz', component: Baz },
{ path: 'with-params/:id', component: WithParams },
// relative redirect to a sibling route
{ path: 'relative-redirect', redirect: 'foo' }
]
},
// absolute redirect
{ path: '/absolute-redirect', redirect: '/bar' },
// dynamic redirect, note that the target route `to` is available for the redirect function
{ path: '/dynamic-redirect/:id?',
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'
}
}
},
// named redirect
{ path: '/named-redirect', redirect: { name: 'baz' }},
// redirect with params
{ path: '/redirect-with-params/:id', redirect: '/with-params/:id' },
// catch all redirect
{ path: '*', redirect: '/' }
]
})
new Vue({
router,
template: `
<div id="app">
Redirect
to="/relative-redirect">
/relative-redirect (redirects to /foo)
to="/relative-redirect?foo=bar">
/relative-redirect?foo=bar (redirects to /foo?foo=bar)
to="/absolute-redirect">
/absolute-redirect (redirects to /bar)
to="/dynamic-redirect">
/dynamic-redirect (redirects to /bar)
to="/dynamic-redirect/123">
/dynamic-redirect/123 (redirects to /with-params/123)
to="/dynamic-redirect?to=foo">
/dynamic-redirect?to=foo (redirects to /foo)
to="/dynamic-redirect#baz">
/dynamic-redirect#baz (redirects to /baz)
to="/named-redirect">
/named-redirect (redirects to /baz)
to="/redirect-with-params/123">
/redirect-with-params/123 (redirects to /with-params/123)
to="/not-found">
/not-found (redirects to /)
"view">
div>
`
}).$mount('#app')
/a的别名是/b,意味着,当用户访问/b时,URL会保持/b,但是路由匹配为/a,就像用户访问/a一样。
对应的路由配置为:
const router = new VueRouter({
routes: [
{ path: '/a', component:A, alias: '/b' }
]
})
别名的功能让我们可以自由地将ui结构映射到任意的URL, 而不是受限于配置的嵌套路由结构