vue-router底层实现
Vue Router 底层实现原理
Vue Router 是 Vue.js 官方的路由管理器,其核心功能包括路由映射、动态路由匹配、路由参数传递、导航守卫等。以下是其底层实现的关键技术点:
路由模式
Vue Router 支持两种路由模式:
- Hash 模式:通过
window.location.hash和hashchange事件实现。URL 中会带有#符号,例如http://example.com/#/home。
优势是兼容性好,无需服务器配置。 - History 模式:基于 HTML5 History API(
pushState、replaceState和popstate事件)。URL 更简洁,例如http://example.com/home。
需要服务器支持,避免直接访问子路由时返回 404。
路由映射与匹配
路由配置通过 routes 数组定义,Vue Router 会将其转换为路由映射表。动态路由(如 /user/:id)通过路径解析和正则匹配实现:

const pathToRegexp = require('path-to-regexp');
const regex = pathToRegexp('/user/:id');
const match = regex.exec('/user/123'); // match.params.id === '123'
响应式路由
Vue Router 通过 Vue 的响应式系统实现路由与组件的动态绑定。核心是通过 currentRoute 对象(Vue 响应式数据)存储当前路由信息:
let _route = {}; // 当前路由对象
Object.defineProperty(this, '$route', {
get() { return _route; },
set(val) { _route = val; } // 变化时触发视图更新
});
导航守卫
导航守卫通过钩子函数队列实现,包括全局守卫、路由独享守卫和组件内守卫。执行流程如下:

- 触发导航(如
router.push)。 - 按顺序调用
beforeEach、beforeRouteUpdate等守卫。 - 解析目标路由,确认导航后调用
afterEach。
路由跳转
路由跳转的核心方法是 push 和 replace,底层调用 History API 或修改 hash:
function push(location) {
if (history.pushState) {
history.pushState({}, '', location); // History 模式
} else {
window.location.hash = location; // Hash 模式
}
}
组件渲染
<router-view> 是动态组件,根据当前路由的 matched 数组渲染对应组件。通过 Vue 的 h 函数动态生成组件:
render(h) {
const matched = this.$route.matched[this.depth];
return matched ? h(matched.components) : null;
}
关键源码模块
- Router 类:核心逻辑入口,初始化路由模式、路由映射和导航守卫。
- History 基类:抽象
HashHistory和HTML5History的公共方法。 - Matcher:处理路由配置的解析和匹配。
- Route 对象:存储当前路由路径、参数、查询等信息。
通过以上机制,Vue Router 实现了与 Vue 深度集成的路由管理功能。






