Skip to content

createMemoryHistory() - 创建内存历史记录

createMemoryHistory() 函数专门用于创建内存中的历史记录管理器,这是 Vue Router 的三种历史模式之一,特别适合服务器端渲染 (SSR)测试环境。🧠

📋 函数签名

typescript
function createMemoryHistory(base?: string): RouterHistory

🎯 功能说明

这个函数创建一个不依赖浏览器 URL 的历史记录管理器,所有路由状态都保存在内存中。想象一下,它就像是给路由系统装了一个"内存硬盘"!

核心特点

  • 无浏览器依赖 - 不操作真实的浏览器 URL
  • 适合 SSR - 服务器端渲染的理想选择
  • 测试友好 - 单元测试的完美搭档
  • 无地址栏同步 - 用户看不到 URL 变化

⚙️ 参数说明

base - 基础路径(可选)

类型默认值说明
string''应用的基础路径,所有路由都会基于此路径

📤 返回值

返回一个 RouterHistory 实例,包含内存历史记录的所有操作方法。

💡 实际应用示例

SSR 环境使用

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

// 服务器端创建路由实例
const router = createRouter({
  history: createMemoryHistory(), // 使用内存历史
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

// 在服务器端渲染时使用
app.use(router)

单元测试场景

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

describe('路由测试', () => {
  it('应该能正确导航', async () => {
    const router = createRouter({
      history: createMemoryHistory(), // 测试环境使用内存历史
      routes: [{ path: '/test', component: TestComponent }]
    })
    
    await router.push('/test')
    expect(router.currentRoute.value.path).toBe('/test')
  })
})

带基础路径的配置

javascript
const router = createRouter({
  history: createMemoryHistory('/app'), // 基础路径为 /app
  routes: [
    { path: '/', component: Home },     // 实际路径为 /app/
    { path: '/user', component: User } // 实际路径为 /app/user
  ]
})

🔄 与其他历史模式的对比

模式适用场景URL 可见性服务器要求
createMemoryHistorySSR、测试❌ 不可见无特殊要求
createWebHistory生产环境✅ 可见需要配置
createWebHashHistory静态部署✅ 可见(带#)无特殊要求

🚨 注意事项

客户端限制

javascript
// 在客户端使用内存历史时,用户无法通过浏览器前进/后退
const router = createRouter({
  history: createMemoryHistory(), // ❌ 不推荐在客户端使用
  routes: [...]
})

路径解析差异

javascript
// 内存历史不会处理真实的 URL 解析
const history = createMemoryHistory()
history.push('/page?query=value') // 查询参数仍在内存中处理

🔗 相关 API

💡 专业建议:在开发 SSR 应用时,根据环境动态选择历史模式:

javascript
const history = typeof window === 'undefined' 
  ? createMemoryHistory() 
  : createWebHistory()

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