Vue 路由配置路径不对,导致点击首页跳转404页面!

0 阅读3分钟

^ 关注我,带你一起学GIS ^

前言

问题是这样的,最近在使用Vue路由时,发现由于一些小的变动,如加"/",或者不加"/"会导致截然不同的效果,在生产实践中直接使得点击首页时,路由跳转到404页面

所以本文特做以下记录,作为研究和分享。

1. 软件环境

本文使用如下软件环境,以供参考。

时间:2026年

系统:Windows 11

Vue:2.6.10

Vue-router:3.0.6

2. 踩坑记录

首先说一下,原始的正确配置记录如下,在空路由的情况下直接重定向到首页。并且应用访问路径需要加上路径前缀,如"/app"。

{
  path: '',
  component: Layout,
  redirect: '/index',
  children: [
    {
      path: 'index',
      name: 'index',
      component: () => import('@/views/home/index'),
      meta: { title: '首页', icon: 'index', noCache: 0 }
    }
  ]
}

现在当我稍加改造子路由的path参数,将index修改为/index,这时问题来了,点击首页已经无法正常访问,会直接跳转404页面。

{
  path: '',
  component: Layout,
  redirect: '/index',
  children: [
    {
      path: '/index',
      name: 'index',
      component: () => import('@/views/home/index'),
      meta: { title: '首页', icon: 'index', noCache: 0 }
    }
  ]
}

产生原因: 在Vue Router中,相对路径不以"/"开头,会与父路径拼接;绝对路径以"/"开头,会忽略父路径,直接作为完整路径。

所以在children中的path以"/"开头,会被当做绝对路径。正常的访问路径为"/app/index",但是此时由于子路径脱离了父级,所以访问路径变成了"/index",导致路由无法正确匹配,便跳转到了404页面。

3. 解决方法

第一种方式,子路径path参数使用相对路径,不需要添加"/"。

{
  path: '',
  component: Layout,
  redirect: '/index',
  children: [
    {
      path: 'index',
      name: 'index',
      component: () => import('@/views/home/index'),
      meta: { title: '首页', icon: 'index', noCache: 0 }
    }
  ]
}

第二种方式,父路由使用绝对路径"/",子路由用相对路径。

{
  path: '/',
  component: Layout,
  redirect: '/index',
  children: [
    {
      path: 'index', // 实际路径 /index
      name: 'index',
      component: () => import('@/views/home/index'),
      meta: { title: '首页', icon: 'index', noCache: 0 }
    }
  ]
}

GIS之路 开发示例数据下载,请在公众号后台回复:vector

全国信息化工程师-GIS 应用水平考试资料,请在公众号后台回复:GIS考试


GIS之路 公众号已经接入了智能助手**,** 可以在对话框进行提问,也可以直接搜索历史文章进行查看。

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !