文章目录
- 一、路由模式实现原理
- 1. Hash 模式
- 2. History 模式
- 二、响应式路由系统
- 1. 路由对象响应化
- 2. 路由映射解析
- 三、组件渲染机制
- 1. RouterView 实现
- 2. 路由匹配流程
- 四、导航守卫系统
- 1. 守卫执行流程
- 2. 守卫类型对比
- 五、核心源码结构
- 六、设计亮点分析
- 七、性能优化策略
- 总结:Vue Router 的实现哲学
Vue Router 是 Vue.js 官方路由管理库,其核心实现原理主要围绕以下几个关键技术点展开。我们将从路由模式、响应式机制、组件渲染三个维度深入剖析其实现细节。
一、路由模式实现原理
1. Hash 模式
class HashHistory {constructor(router) {this.router = router// 初始化监听hash变化window.addEventListener('hashchange', () => {this.onHashChange()})}onHashChange() {const path = window.location.hash.slice(1) // 获取#后的路径this.router._route = path // 触发路由更新}push(path) {window.location.hash = '#' + path}
}
核心机制:
- 通过
window.location.hash
操作 URL - 监听
hashchange
事件实现路由切换 - 兼容性好(支持 IE8+)
2. History 模式
class HTML5History {constructor(router) {this.router = router// 监听浏览器前进后退window.addEventListener('popstate', (e) => {const path = window.location.pathnamethis.router._route = path})}push(path) {window.history.pushState({}, '', path)this.router._route = path}
}
核心机制:
- 使用
history.pushState
和replaceState
API - 监听
popstate
事件处理导航 - 需要服务端支持(避免404问题)
二、响应式路由系统
1. 路由对象响应化
class VueRouter {constructor(options) {// 创建响应式路由对象this._route = new Vue({data() {return {current: '/'}}})}get currentPath() {return this._route.current}
}
2. 路由映射解析
function createRouteMap(routes) {const pathMap = Object.create(null)routes.forEach(route => {addRouteRecord(pathMap, route)})return {pathMap}
}function addRouteRecord(pathMap, route, parent) {const path = parent ? `${parent.path}/${route.path}` : route.pathconst record = {path,component: route.component,parent}if (!pathMap[path]) {pathMap[path] = record}route.children && route.children.forEach(child => {addRouteRecord(pathMap, child, record)})
}
三、组件渲染机制
1. RouterView 实现
const RouterView = {functional: true,render(h, { parent, data }) {const route = parent.$routeconst matched = route.matcheddata.routerView = truelet depth = 0while (parent && parent._routerRoot !== parent) {if (parent.$vnode && parent.$vnode.data.routerView) {depth++}parent = parent.$parent}const record = matched[depth]return h(record.component, data)}
}
2. 路由匹配流程
四、导航守卫系统
1. 守卫执行流程
function runQueue(queue, fn, cb) {const step = index => {if (index >= queue.length) return cb()const hook = queue[index]fn(hook, () => step(index + 1))}step(0)
}// 完整的导航解析流程
function resolveAsyncComponents(matched) {return (to, from, next) => {let hasAsync = falselet pending = 0matched.forEach(match => {if (typeof match.components.default === 'function') {hasAsync = truepending++match.components.default(resolved => {match.components.default = resolvedpending--if (pending === 0) next()})}})if (!hasAsync) next()}
}
2. 守卫类型对比
守卫类型 | 执行时机 | 返回值处理 |
---|---|---|
全局前置守卫 | 导航触发前 | 可取消导航 |
路由独享守卫 | 进入特定路由前 | 可重定向到其他路由 |
组件内守卫 | 组件生命周期阶段 | 可终止组件加载 |
全局解析守卫 | 所有组件解析完成后 | 最后确认导航 |
全局后置钩子 | 导航完成后 | 无返回值处理 |
五、核心源码结构
src/
├── components/ # 路由组件
│ ├── link.js # router-link实现
│ └── view.js # router-view实现
├── history/ # 路由模式
│ ├── base.js # 基础类
│ ├── hash.js # Hash模式
│ └── html5.js # History模式
├── create-matcher.js # 路由匹配器
├── create-route-map.js # 路由映射表
├── index.js # 主入口文件
└── install.js # Vue插件安装
六、设计亮点分析
-
响应式路由对象
- 通过 Vue 实例实现响应式数据绑定
- 自动触发组件更新
-
动态路由匹配
- 支持参数匹配:
/user/:id
- 支持通配符:
/user/*
- 支持参数匹配:
-
嵌套路由系统
const routes = [{path: '/user',component: User,children: [{ path: 'profile', component: Profile },{ path: 'posts', component: Posts }]} ]
-
滚动行为控制
const router = new VueRouter({scrollBehavior(to, from, savedPosition) {return savedPosition || { x: 0, y: 0 }} })
七、性能优化策略
-
路由懒加载
const User = () => import('./User.vue')
-
组件缓存
<keep-alive><router-view></router-view> </keep-alive>
-
路由预加载
router.beforeEach((to, from, next) => {if (to.meta.preload) {to.matched.forEach(match => {match.components.default()})}next() })
总结:Vue Router 的实现哲学
-
插件化架构
通过 Vue 插件系统注入$router
和$route
-
模式抽象
统一封装 Hash 和 History 模式 -
响应式驱动
基于 Vue 的响应式系统自动更新视图 -
可扩展设计
支持自定义路由匹配规则
理解这些核心原理有助于:
- 深度定制路由行为
- 高效排查路由问题
- 开发高级路由功能
- 优化大型应用路由性能
完整实现代码可参考 Vue Router 源码仓库:github.com/vuejs/vue-router