vue router的实现
Vue Router 的实现原理
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。其核心实现基于以下几个关键机制:
路由模式
Vue Router 支持两种路由模式:
- Hash 模式:通过 URL 的 hash 部分(
#)实现路由切换,兼容性好,无需服务器配置。const router = new VueRouter({ mode: 'hash', routes: [...] }); - History 模式:利用 HTML5 History API 的
pushState和replaceState方法实现无#的 URL,需服务器支持。const router = new VueRouter({ mode: 'history', routes: [...] });
路由匹配
路由匹配通过 routes 配置完成,Vue Router 会解析当前 URL 并与路由配置进行匹配,找到对应的组件。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
动态路由
支持参数化路由,通过 : 标记动态路径片段。
const routes = [
{ path: '/user/:id', component: User }
];
在组件中可通过 $route.params.id 访问参数。
导航守卫
提供全局或路由独享的守卫函数,用于控制导航行为。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
路由组件渲染
通过 <router-view> 动态渲染匹配的组件,<router-link> 生成导航链接。
<router-link to="/about">About</router-link>
<router-view></router-view>
核心实现细节
响应式路由
Vue Router 利用 Vue 的响应式系统,将当前路由信息注入到根实例的 $route 属性中。当路由变化时,相关组件会自动更新。
路由切换流程
- 用户触发导航(如点击
<router-link>或调用router.push)。 - 解析目标路由,执行导航守卫。
- 确认导航后,更新 URL 并渲染对应组件。
源码结构
Vue Router 的核心源码模块包括:
- matcher:处理路由配置和匹配逻辑。
- history:抽象不同路由模式(Hash/History)的实现。
- components:实现
<router-view>和<router-link>。
插件机制
Vue Router 通过 Vue.use() 安装,将 $router 和 $route 注入到每个组件实例中。
Vue.mixin({
beforeCreate() {
if (this.$options.router) {
this._routerRoot = this;
this._router = this.$options.router;
this._router.init(this);
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
}
}
});
通过以上机制,Vue Router 实现了单页面应用的路由管理功能,支持动态路由、导航控制和组件渲染。







