Skip to content

createWebHistory | Vue Router API

概述

createWebHistory 函数用于创建 HTML5 历史模式的路由器历史记录实例。这是现代单页应用程序推荐使用的历史模式,它使用浏览器的 History API 来管理路由状态。

语法

typescript
function createWebHistory(base?: string): RouterHistory

参数

base

类型: string必需: 否 说明: 应用的基础路径,所有路由都会相对于这个路径进行解析

返回值

类型: RouterHistory说明: 配置好的历史记录实例,用于传递给 createRouter

基本用法

创建基础历史记录

javascript
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

使用基础路径

javascript
// 如果应用部署在 /app/ 目录下
const router = createRouter({
  history: createWebHistory('/app/'),
  routes: [
    { path: '/', component: Home },        // 实际路径: /app/
    { path: '/about', component: About }    // 实际路径: /app/about
  ]
})

工作原理

HTML5 History API

createWebHistory 基于浏览器的 History API 实现:

  • pushState() - 添加新的历史记录
  • replaceState() - 替换当前历史记录
  • popstate 事件 - 监听浏览器前进后退

URL 结构

使用 HTML5 历史模式时,URL 看起来像普通的多页应用:

// 传统多页应用
https://example.com/about

// Vue Router (HTML5 历史模式)
https://example.com/about

实际应用场景

场景 1:生产环境部署

javascript
// 根据环境变量设置基础路径
const base = process.env.NODE_ENV === 'production' 
  ? '/my-app/' 
  : '/'

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

场景 2:多租户应用

javascript
// 根据租户设置不同的基础路径
function getTenantBasePath() {
  const hostname = window.location.hostname
  if (hostname.includes('tenant1')) {
    return '/tenant1/'
  } else if (hostname.includes('tenant2')) {
    return '/tenant2/'
  }
  return '/'
}

const router = createRouter({
  history: createWebHistory(getTenantBasePath()),
  routes: [...]
})

场景 3:子目录部署

javascript
// 应用部署在子目录 /blog/ 下
const router = createRouter({
  history: createWebHistory('/blog/'),
  routes: [
    { path: '/', component: BlogHome },           // 访问: /blog/
    { path: '/post/:id', component: BlogPost },    // 访问: /blog/post/123
    { path: '/about', component: BlogAbout }       // 访问: /blog/about
  ]
})

服务器配置要求

Apache 配置 (.htaccess)

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

Nginx 配置

nginx
location / {
  try_files $uri $uri/ /index.html;
}

Express.js 配置

javascript
const express = require('express')
const app = express()
const history = require('connect-history-api-fallback')

app.use(history())
app.use(express.static('dist'))

高级用法

自定义历史记录行为

javascript
import { createWebHistory } from 'vue-router'

const history = createWebHistory('/app/')

// 监听历史记录变化
window.addEventListener('popstate', (event) => {
  console.log('历史记录变化:', event.state)
})

// 手动添加历史记录
history.push('/custom-path', { customData: 'value' })

与状态管理集成

javascript
import { createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'

const history = createWebHistory()

// 保存导航状态到历史记录
function navigateWithState(to, state) {
  history.push(to, state)
}

// 从历史记录恢复状态
window.addEventListener('popstate', (event) => {
  if (event.state) {
    // 恢复应用状态
    appStore.restoreState(event.state)
  }
})

最佳实践

1. 正确的 base 路径配置

javascript
// 自动检测基础路径
function getAutoBasePath() {
  const path = window.location.pathname
  const segments = path.split('/').filter(Boolean)
  
  if (segments.length > 0) {
    return `/${segments[0]}/`
  }
  
  return '/'
}

const router = createRouter({
  history: createWebHistory(getAutoBasePath()),
  routes: [...]
})

2. 错误处理

javascript
try {
  const history = createWebHistory('/app/')
  const router = createRouter({
    history,
    routes: [...]
  })
} catch (error) {
  console.error('历史记录创建失败:', error)
  // 降级到哈希模式
  const router = createRouter({
    history: createWebHashHistory(),
    routes: [...]
  })
}

3. 性能优化

javascript
// 延迟加载历史模式(大型应用)
async function createRouterWithLazyHistory() {
  const { createWebHistory } = await import('vue-router')
  
  return createRouter({
    history: createWebHistory(),
    routes: [...]
  })
}

与哈希模式对比

HTML5 历史模式优势

  • 美观的 URL - 没有 # 符号
  • SEO 友好 - 搜索引擎可以正确索引
  • 更好的用户体验 - URL 看起来更自然

哈希模式优势

  • 服务器配置简单 - 不需要特殊配置
  • 兼容性更好 - 支持旧版本浏览器

注意事项

  1. 服务器配置 - 必须配置服务器支持 HTML5 历史模式
  2. 基础路径 - 确保基础路径与部署环境匹配
  3. 相对路径 - 使用相对路径时注意基础路径的影响
  4. CDN 部署 - 在 CDN 上部署时需要特殊配置

兼容性

  • 现代浏览器(Chrome, Firefox, Safari, Edge)
  • 需要服务器端配置支持
  • 不支持 IE11 及以下版本

🚀 提示:对于现代 Web 应用,HTML5 历史模式是推荐的选择。它提供了更好的用户体验和 SEO 效果,只需要确保服务器正确配置即可。

🚀 Vue Router - 让前端路由变得简单而强大 | 构建现代化单页应用的最佳选择