若依Vue 项目多子路径配置

Vue 项目多子路径配置文档

一、需求说明

在现有 Vue 项目中,已配置 /linyi/ 子路径,现需同时支持 /dongyin/ 子路径访问。

二、解决方案概述

需要修改两个文件:

  1. vue.config.js:将 publicPath 改为相对路径,使静态资源可在任意子路径下正确加载
  2. src/router/index.js:将路由的 base 改为动态获取,根据当前 URL 自动判断使用哪个子路径

三、详细修改步骤

3.1 修改 vue.config.js

文件位置 :vue.config.js

修改内容 :将 publicPath 从固定路径改为相对路径

修改前:

javascript 复制代码
publicPath: process.env.NODE_ENV === "production" ? "/linyi" : "/linyi",

修改后:

javascript 复制代码
publicPath: process.env.NODE_ENV === "production" ? "./" : "./",

说明:

  • 使用相对路径 "./" 后,静态资源(JS、CSS、图片等)会根据当前访问路径自动调整
  • 无论通过 /linyi/ 还是 /dongyin/ 访问,静态资源都能正确加载

3.2 修改 src/router/index.js

文件位置 :src/router/index.js

修改内容:添加动态获取路由 base 的函数,并应用到 Router 配置中

修改前:

javascript 复制代码
export default new Router({
  base:'/linyi',
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

修改后:

javascript 复制代码
// 动态获取路由 base 路径,支持 /linyi 和 /dongyin
function getRouterBase() {
  const pathname = window.location.pathname
  // 检查是否以 /linyi 或 /dongyin 开头
  if (pathname.startsWith('/linyi')) {
    return '/linyi'
  } else if (pathname.startsWith('/dongyin')) {
    return '/dongyin'
  }
  // 默认返回 /linyi
  return '/linyi'
}

export default new Router({
  base: getRouterBase(),
  mode: 'history', // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

说明:

  • getRouterBase() 函数根据当前 URL 路径自动判断应该使用哪个 base
  • 如果路径以 /linyi 开头,返回 /linyi
  • 如果路径以 /dongyin 开头,返回 /dongyin
  • 默认返回 /linyi 作为兜底

四、完整代码示例

4.1 vue.config.js 完整配置(关键部分)

javascript 复制代码
module.exports = {
  // 部署生产环境和开发环境下的URL
  // 使用相对路径,支持多个子路径访问
  publicPath: process.env.NODE_ENV === "production" ? "./" : "./",
  
  // 在npm run build 或 yarn build 时,生成文件的目录名称
  outputDir: 'dist',
  
  // 用于放置生成的静态资源 (js、css、img、fonts) 的
  assetsDir: 'static',
  
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建
  productionSourceMap: false,
  
  // ... 其他配置保持不变
}

4.2 src/router/index.js 完整配置(关键部分)

javascript 复制代码
// ... 路由定义代码 ...

// 动态获取路由 base 路径,支持 /linyi 和 /dongyin
function getRouterBase() {
  const pathname = window.location.pathname
  // 检查是否以 /linyi 或 /dongyin 开头
  if (pathname.startsWith('/linyi')) {
    return '/linyi'
  } else if (pathname.startsWith('/dongyin')) {
    return '/dongyin'
  }
  // 默认返回 /linyi
  return '/linyi'
}

// 防止连续点击多次路由报错
let routerPush = Router.prototype.push
let routerReplace = Router.prototype.replace
// push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}
// replace
Router.prototype.replace = function push(location) {
  return routerReplace.call(this, location).catch(err => err)
}

export default new Router({
  base: getRouterBase(),
  mode: 'history', // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

五、生产环境服务器配置

5.1 Nginx 配置示例

如果使用 Nginx 作为 Web 服务器,需要配置两个 location 都指向同一个应用目录:

nginx 复制代码
server {
    listen 80;
    server_name your-domain.com;

    # /linyi 路径配置
    location /linyi {
        alias /path/to/your/dist;
        try_files $uri $uri/ /linyi/index.html;
        index index.html;
    }

    # /dongyin 路径配置
    location /dongyin {
        alias /path/to/your/dist;
        try_files $uri $uri/ /dongyin/index.html;
        index index.html;
    }
}

配置说明:

  • 两个 location 都指向同一个 dist 目录
  • try_files 确保 Vue Router 的 history 模式正常工作
  • 当访问不存在的路径时,会回退到对应的 index.html

5.2 Apache 配置示例

如果使用 Apache,可以在 .htaccess 文件中配置:

apache 复制代码
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /linyi/
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /linyi/index.html [L]
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /dongyin/
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /dongyin/index.html [L]
</IfModule>

六、测试验证

6.1 开发环境测试

  1. 启动开发服务器:npm run dev
  2. 访问 http://localhost/linyi/,确认应用正常加载
  3. 访问 http://localhost/dongyin/,确认应用正常加载
  4. 测试路由跳转,确认两个路径下的路由都正常工作

6.2 生产环境测试

  1. 构建项目:npm run build:prod
  2. 将 dist 目录部署到服务器
  3. 配置服务器(Nginx/Apache)支持两个路径
  4. 分别访问两个路径,确认功能正常

七、注意事项

  1. 相对路径 vs 绝对路径

    • 使用相对路径 "./" 后,静态资源会根据当前访问路径自动调整
    • 如果后续需要添加更多子路径,无需修改 publicPath
  2. 路由 base 动态获取

    • getRouterBase() 函数在应用初始化时执行
    • 确保在创建 Router 实例之前,window.location.pathname 已经可用
  3. 扩展性

    • 如果需要支持更多子路径(如 /path3、/path4),只需在 getRouterBase() 函数中添加相应的判断逻辑
  4. 兼容性

    • 此方案兼容 Vue Router 的 history 模式
    • 确保服务器正确配置了回退到 index.html 的规则
  5. 环境变量

    • 如果项目中有使用环境变量来配置 base URL,可能需要相应调整

八、扩展:支持更多子路径

如果需要支持更多子路径,可以修改 getRouterBase() 函数:

javascript 复制代码
function getRouterBase() {
  const pathname = window.location.pathname
  // 支持的子路径列表
  const supportedPaths = ['/linyi', '/dongyin', '/path3', '/path4']
  
  // 查找匹配的路径
  for (const path of supportedPaths) {
    if (pathname.startsWith(path)) {
      return path
    }
  }
  
  // 默认返回 /linyi
  return '/linyi'
}

九、常见问题

Q1: 修改后静态资源加载失败?

A : 检查 publicPath 是否正确设置为 "./",并确认服务器配置正确。

Q2: 路由跳转后路径不正确?

A : 确认 getRouterBase() 函数逻辑正确,并且 Router 的 base 配置已应用。

Q3: 生产环境访问 404?

A : 检查服务器配置,确保 try_files 或 RewriteRule 正确配置,所有路径都回退到对应的 index.html。

Q4: 如何验证配置是否生效?

A:

  • 打开浏览器开发者工具,查看 Network 标签,确认静态资源路径正确
  • 查看 Console,确认没有路径相关的错误
  • 测试路由跳转,确认 URL 变化正确

文档版本 :v1.0
最后更新 :2024年
适用项目:Vue 2.x + Vue Router 3.x

相关推荐
bai27320 分钟前
path.join('C:\a', '\b') 给我 C:\a\b,path.resolve 给 C:\b:Windows 上 51 行路径实测
javascript·后端
kyriewen40 分钟前
我写的 12 个 AI Skill,三个月后 8 个在吃空饷
javascript·人工智能·程序员
北城笑笑2 小时前
Vue 112 ,下篇:前端 dist 还原成 Vue3 + Vite 项目( krpano 全景接入与页面适配实战,Vue2 → Vue3 )
前端·javascript·vue.js·3d·前端框架·vue·webgl
我叫黑大帅2 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
KevinWang_2 小时前
iOS 开发计划(三) - 打印 JavaScript 调试日志
javascript
如夏倾城4 小时前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化5 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter5 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞5 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger6 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis