vue-router - 重定向和别名

261 阅读2分钟

我正在参加「掘金·启航计划」

重定向

重定向是指当用户访问某个 URL 时,路由系统将会把该 URL 重定向到另一个 URL。例如,当用户访问 /home 时,路由系统会把该 URL 重定向到 /,然后匹配成 /

重定向是通过路由配置中的 redirect 属性实现的

const routes = [
  { path: '/home', redirect: '/' }
];

重定向的目标也可以是一个命名的路由

const routes = [
  { path: '/home', redirect: { name: 'homepage' } }
];

也可以是一个方法,动态返回重定向目标

const routes = [
  {
    // /search/screens -> /search?q=screens
    path: '/search/:searchText',
    // to 参数表示当前即将达到的路由对象,即 /search/:searchText 对应的路由对象
    redirect: to => {
      // 需要返回重定向的路径字符串/路径对象
      return { path: '/search', query: { q: to.params.searchText } }
    },
  },
  {
    path: '/search',
    // ...
  },
]

在编写重定向时,可以省略组件配置,因为它从未被直接访问过,因此没有组件需要渲染

唯一的例外是嵌套路由:如果一个路由记录有 childrenredirect 属性,它也应该有 component 属性

const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    children: [
      {
        path: '',
        component: Home,
      },
      {
        path: 'profile',
        component: Profile,
        redirect: 'settings',
        children: [
          {
            path: 'settings',
            component: ProfileSettings,
          },
          {
            path: 'password',
            component: ProfilePassword,
          },
        ],
      },
    ],
  },
];

相对重定向

const routes = [
  {
    // 如果一个路由记录没有 children 属性,那么它的重定向规则将会是最后一个片段的替换
    // 如果该路由拥有children属性,那么它的重定向规则是路径的拼接
    // /users/123/posts -> /users/123/profile
    path: '/users/:id/posts',
    redirect: to => {
      // return 'profile' 等价于  return { path: 'profile'}
      return 'profile'
    },
  },
]

别名

别名是指给一个路由路径定义一个或多个别名路径。当用户访问这些别名路径时,路由系统会把它们匹配为该路由路径。这样可以自由地将 UI 结构映射到任意的 URL,而不受路由配置的嵌套结构的限制

例如将 / 别名为 /home,意味着当用户访问 /home 时,URL 仍然是 /home,但会被匹配为用户正在访问 /

const routes = [{ path: '/', component: Homepage, alias: '/home' }]
const routes = [
  {
    path: '/users',
    component: UsersLayout,
    children: [
      // 为这 3 个 URL 呈现 UserList
      // - /users
      // - /users/list
      // - /people
      { path: '', component: UserList, alias: ['/people', 'list'] },
    ],
  },
]

如果你的路由有动态路径参数,请确保在任何绝对别名中包含它们

const routes = [
  {
    path: '/users/:id',
    component: UsersByIdLayout,
    children: [
      // 为这 3 个 URL 呈现 UserDetails
      // - /users/24
      // - /users/24/profile
      // - /24
      { path: 'profile', component: UserDetails, alias: ['/:id', ''] },
    ],
  },
]