You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Router v2迁移至v3:如何保留子路由相对重定向原行为?

Vue3路由中实现空路径命名子路由的相对重定向(兼容Vue2旧行为)

Vue3路由迁移后,空路径的命名子路由不再自动追加斜杠,导致原本指向/parent/home的重定向会直接跳转到/home。要恢复Vue2的旧行为,实现相对重定向到/parent/home,可以用以下两种方法:

方法一:使用动态重定向函数拼接路径

通过重定向函数获取当前路由的完整路径,手动拼接子路由的路径,确保重定向指向父路由下的子路径:

const routes = [
  {
    path: '/parent',
    component: Parent,
    children: [
      {
        path: '',
        redirect: (to) => {
          // 基于当前父路由的完整路径,拼接子路由home的路径
          return `${to.fullPath}/home`;
        }
      },
      {
        path: 'home',
        name: 'Home',
        component: Home
      }
    ]
  }
];

方法二:利用命名路由的相对重定向特性

给父路由设置名称,然后在重定向时使用relative: true选项,让路由解析相对于当前父路由:

const routes = [
  {
    path: '/parent',
    name: 'Parent',
    component: Parent,
    children: [
      {
        path: '',
        // 相对父路由解析命名路由Home
        redirect: { name: 'Home', relative: true }
      },
      {
        path: 'home',
        name: 'Home',
        component: Home
      }
    ]
  }
];

第二种方法更符合Vue3路由的设计规范,推荐优先使用。

内容的提问来源于stack exchange,提问作者Luckylooke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:55:14