1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
# 重定向和别名
## 重定向
重定向也是通过 `routes` 配置来完成,下面例子是从 `/a` 重定向到 `/b`:
``` js
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' }
]
})
```
重定向的目标也可以是一个命名的路由:
``` js
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})
```
甚至是一个方法,动态返回重定向目标:
``` js
const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})
```
注意[导航守卫](../advanced/navigation-guards.md)并没有应用在跳转路由上,而仅仅应用在其目标上。在下面这个例子中,为 `/a` 路由添加一个 `beforeEnter` 守卫并不会有任何效果。
其它高级用法,请参考[例子](https://github.com/vuejs/vue-router/blob/dev/examples/redirect/app.js)。
## 别名
“重定向”的意思是,当用户访问 `/a`时,URL 将会被替换成 `/b`,然后匹配路由为 `/b`,那么“别名”又是什么呢?
**`/a` 的别名是 `/b`,意味着,当用户访问 `/b` 时,URL 会保持为 `/b`,但是路由匹配则为 `/a`,就像用户访问 `/a` 一样。**
上面对应的路由配置为:
``` js
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
```
“别名”的功能让你可以自由地将 UI 结构映射到任意的 URL,而不是受限于配置的嵌套路由结构。
更多高级用法,请查看[例子](https://github.com/vuejs/vue-router/blob/dev/examples/route-alias/app.js)。
|