🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[success] # 路由重定向 1. **路由重定向**,将指定连接重定向分发给给其他连接,常见的场景一半在路由访问时候我们一般会定义一个首页路由例如`/home`,但大多数情况希望用户输入'/' 时候也可以匹配进入`/home` 首页,可以采用形式 ~~~ [ { path: "/", name: "home", component: HomeView, }, { path: "/home", name: "home1", component: HomeView, }], ~~~ 这么写过于复杂可以采用**路由重定向**形式,但和上面不同是当访问`/` 路径时候浏览器url 实际最后会显示为`/home` ~~~ [ { path: "/", redirect: "/home", }, { path: "/home", name: "home1", component: HomeView, }, ] ~~~ * 也可以采用命名路由指定重定向位置 ~~~ const routes = [{ path: '/home', redirect: { name: 'homepage' } }] ~~~ >[danger] ##### 嵌套路由重定向 1. 在写`redirect`的时候,可以省略`component`配置,因为它从来没有被直接访问过,所以没有组件要渲染。唯一的例外是[嵌套路由](https://router.vuejs.org/zh/guide/essentials/nested-routes.html) 2. 嵌套路由为什么要使用重定向 定位到子路由,之前嵌套路由提过可以单独访问父级路径并且也会展示,但大部分情况是想展示的更多是包含子路由的组件,就可以呃使用重定向 ~~~ { path: '/about', name: 'About', component: LAYOUT, redirect: '/about/index', meta: { hideChildrenInMenu: true, icon: 'simple-icons:about-dot-me', title: t('routes.dashboard.about'), orderNo: 100000, }, children: [ { path: 'index', name: 'AboutPage', component: () => import('/@/views/sys/about/index.vue'), meta: { title: t('routes.dashboard.about'), icon: 'simple-icons:about-dot-me', hideMenu: true, }, }, ], }; ~~~ >[danger] ##### 重定向和路由守卫 在路由重定向的时候路由守卫只会触发最后实际访问的路由,也就是说以最终实际访问的为准 >[danger] ##### 重定向可以是用方法 1. 重定向到相对位置 ~~~ const routes = [ { // 将总是把/users/123/posts重定向到/users/123/profile。 path: '/users/:id/posts', redirect: to => { // 该函数接收目标路由作为参数 // 相对位置不以`/`开头 // 或 { path: 'profile'} return 'profile' }, }, ] ~~~ >[success] # 路由别名 1. `alias` 用来设置路由别名,和重定向不同,当设置重定向时候你最后输入的路径都会变为重定向的目标路由,例如将'/' 重定向到了'/home' 你输入 '/' 在浏览器地址栏最后显示为'/home' ,路由别名就是顾名思义就是两种路由访问都可以进入同一个页面 ~~~ { path: "/home", alias: "/", name: "home1", component: HomeView, }, ~~~ 访问'/' 和 '/home' 都可以访问到`HomeView` 2. 数组形式可以为一个路由设置多个别名 3. 可以给嵌套路由设置和上级一样的别名,来达到访问时候可以直接进入子路由,下面案例中`/about` 、`/about/home`、`/about/list` 、`/aa` 路径访问效果都等同 `/about/home`,也可以利用别的解决嵌套路由重定向问题,**注意** 如果别名路径中前缀是`/`以使嵌套路径中的路径成为绝对路径 ~~~ { path: "/about", name: "about", component: () => import(/* webpackChunkName: "about" */ "../views/AboutView.vue"), children: [ { path: "home", alias: ["/about", "list",'/aa'], component: () => import(/* webpackChunkName: "about" */ "../views/HomeView.vue"), }, ], }, ~~~ * 其他案例一 ~~~ const routes = [ { path: '/users', component: UsersLayout, children: [ // 为这 3 个 URL 呈现 UserList // - /users // - /users/list // - /people { path: '', component: UserList, alias: ['/people', 'list'] }, ], }, ] ~~~ * 其他案例二,如果你的路由有参数,请确保在任何绝对别名中包含它们,也可像下面案例中将别名设置空这样 `/users/:id/ 空` 就指向了`UserDetails ` ~~~ { path: '/users/:id', component: UsersByIdLayout, children: [ // 为这 3 个 URL 呈现 UserDetails // - /users/24 // - /users/24/profile // - /24 { path: 'profile', component: UserDetails, alias: ['/:id', ''] }, ], }, ~~~