在 Vue Router 4 中,如何设置base参数

在 Vue Router 4 中,base参数应该设置在 createWebHistory()函数中。以下是完整的设置方法:

1. 基本设置

复制代码
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory('/your-base-path/'),  // 在这里设置 base
  routes,
})

2. 不同场景的配置

场景一:部署在子目录

复制代码
// 例如:https://example.com/admin/
const router = createRouter({
  history: createWebHistory('/admin/'),
  routes,
})

场景二:部署在根目录

复制代码
// 默认部署在根目录
const router = createRouter({
  history: createWebHistory(),  // 不传参数,默认为根目录
  // 或者显式指定
  history: createWebHistory('/'),
  routes,
})

场景三:动态配置(推荐)

复制代码
// 使用环境变量
const base = import.meta.env.BASE_URL || '/'

const router = createRouter({
  history: createWebHistory(base),
  routes,
})

3. 配合构建工具的配置

使用 Vite

复制代码
// vite.config.js
export default defineConfig({
  base: '/my-app/',  // 这里设置构建时的 base
  // ...
})

// router/index.js
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

使用 Vue CLI

复制代码
// vue.config.js
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' 
    ? '/production-sub-path/' 
    : '/'
}

// router/index.js
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
})

4. 完整示例

复制代码
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
]

// 如果应用部署在 https://example.com/my-app/
const router = createRouter({
  history: createWebHistory('/my-app/'),
  routes,
})

export default router

注意事项

  1. base 必须以斜杠开头和结尾

    复制代码
    // 正确
    createWebHistory('/my-app/')
    
    // 错误
    createWebHistory('my-app')
    createWebHistory('/my-app')
  2. 实际访问 URL

    • 设置 base: '/my-app/'

    • /about路由的实际访问 URL 是:https://example.com/my-app/about

  3. 开发环境和生产环境

    • 开发环境通常使用 /

    • 生产环境根据实际部署路径设置

  4. 服务器配置

    • 需要确保服务器正确配置,将所有路由重定向到 index.html

选择最适合你项目部署场景的配置方式即可。

相关推荐
Lovely_Ruby2 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·后端
kong@react2 小时前
react+ts项目,富文本开发(wangEditor)
前端·react.js·前端框架
重铸码农荣光2 小时前
AI First + Mobile First:用大模型重构下一代应用开发范式
前端·架构·llm
Lovely_Ruby2 小时前
前端er Go-Frame 的学习笔记:实现 to-do 功能(二),前端项目的开发,对接后端
前端
Cassie燁2 小时前
el-button源码解读4——props color和native-type
vue.js·element
willingtolove2 小时前
使用chrome修改请求参数重新发送请求
前端·chrome
-曾牛2 小时前
CSRF跨站请求伪造:原理、利用与防御全解析
前端·网络·web安全·网络安全·渗透测试·csrf·原理解析
大佐不会说日语~2 小时前
SSE 流式输出 Markdown 实时渲染问题解决方案
java·vue.js·sse·spring ai·前端实时渲染
卓码软件测评2 小时前
第三方软件检测机构:【利用测试工具Postman测试沙箱:在Tests标签中编写健壮的质量检查逻辑测试脚本】
javascript·node.js·postman