Skip to content

Vue Router 核心功能实现

这是一个简化版的 Vue Router 实现,展示了路由系统的核心功能。

项目结构

04-core-feature/
├── src/
│   ├── router.js          # 路由器
│   ├── route.js           # 路由
│   └── history.js        # 历史管理
├── test/
│   └── router.test.js
├── package.json
└── README.md

核心功能

1. 路由器

管理应用的路由。

功能:

  • 路由匹配
  • 路由守卫
  • 路由参数

2. 路由

定义单个路由。

功能:

  • 路径匹配
  • 组件映射
  • 嵌套路由

3. 历史管理

管理浏览器历史。

功能:

  • URL 同步
  • 导航控制
  • 历史记录

使用方法

安装依赖

bash
npm install

运行测试

bash
npm test

实现细节

路由匹配

使用正则表达式匹配路由:

javascript
function matchRoute(path, route) {
  const regex = new RegExp('^' + route.path.replace(/:\w+/g, '([^/]+)') + '$')
  const match = path.match(regex)
  
  if (match) {
    return {
      route,
      params: extractParams(match, route.path)
    }
  }
  
  return null
}

路由守卫

在导航前后执行守卫:

javascript
async function runGuards(to, from, next) {
  // beforeEach
  for (const guard of beforeEachGuards) {
    const result = await guard(to, from)
    if (result !== undefined) {
      return result
    }
  }
  
  // 组件内守卫
  // ...
}

历史管理

使用 History API 管理导航:

javascript
function pushState(path) {
  window.history.pushState({}, '', path)
  window.dispatchEvent(new PopStateEvent('popstate'))
}

应用场景

  • 单页应用 - SPA 路由管理
  • 权限控制 - 路由守卫
  • 动态路由 - 动态加载组件
  • 嵌套路由 - 复杂布局

总结

这个实现展示了 Vue Router 的核心概念和架构,包括:

  1. 路由器 - 路由管理和匹配
  2. 路由 - 路由定义和配置
  3. 历史管理 - 浏览器历史同步

通过这个实现,可以深入理解路由系统的原理和设计理念。