若依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_filesRewriteRule 正确配置,所有路径都回退到对应的 index.html

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

A:

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

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

相关推荐
暴力袋鼠哥31 分钟前
基于 Spring Boot 3 + Vue 3 的农产品在线销售平台设计与实现
vue.js·spring boot·后端
chilavert3181 小时前
技术演进中的开发沉思-371:final 关键字(中)
java·前端·数据库
2301_816997881 小时前
Vite构建工具
前端
yuki_uix2 小时前
深入理解 reduce:从面试题到设计思维
前端
凌云拓界2 小时前
TypeWell全攻略(二):热力图渲染引擎,让键盘发光
前端·后端·python·计算机外设·交互·pyqt·数据可视化
coding随想2 小时前
TypeScript 高级类型全攻略:从“可表达性”到“类型体操”的实践之路
前端·javascript·typescript
大时光2 小时前
gsap -滚动插件 ScrollTrigger 简单demo
前端
tangbin5830853 小时前
iOS Swift:蓝牙 BLE 连接外设CoreBluetooth
前端