vue实现路由的原理
Vue 路由实现原理
Vue 路由的核心是通过监听 URL 变化,动态匹配路由配置,并渲染对应的组件。以下是其核心实现机制:
路由模式
Vue Router 支持两种路由模式:
-
Hash 模式:通过
window.location.hash监听 URL 中#后的变化。
特点:兼容性好,无需服务器配置。
示例 URL:http://example.com/#/home -
History 模式:基于 HTML5 History API(
pushState、replaceState)。
特点:URL 更简洁,但需服务器支持。
示例 URL:http://example.com/home
核心实现步骤
1. 路由表映射
通过 routes 配置定义路径与组件的映射关系。

const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
2. 路由监听
- Hash 模式:监听
hashchange事件。 - History 模式:监听
popstate事件(用户点击后退/前进按钮时触发)。
3. 动态渲染
根据当前 URL 匹配路由配置,通过 <router-view> 动态渲染对应组件。
关键源码逻辑(简化版)
class Router {
constructor(options) {
this.routes = options.routes;
this.mode = options.mode || 'hash';
// 初始化监听
if (this.mode === 'hash') {
window.addEventListener('hashchange', this.handleHashChange.bind(this));
} else {
window.addEventListener('popstate', this.handlePopState.bind(this));
}
}
handleHashChange() {
const path = window.location.hash.slice(1) || '/';
this.matchComponent(path);
}
handlePopState() {
const path = window.location.pathname;
this.matchComponent(path);
}
matchComponent(path) {
const route = this.routes.find(route => route.path === path);
if (route) {
// 渲染对应组件到 <router-view>
this.currentComponent = route.component;
}
}
}
路由跳转方法
-
编程式导航:通过
router.push()或router.replace()修改 URL。
Hash 模式底层调用window.location.hash,History 模式调用history.pushState()。
-
声明式导航:通过
<router-link>组件生成<a>标签,拦截点击事件避免页面刷新。
注意事项
-
History 模式需服务器支持
需配置服务器在所有路径返回index.html,避免 404 错误。 -
路由守卫
通过beforeEach等钩子实现权限控制或数据预加载。 -
动态路由
支持path: '/user/:id'的动态路径匹配,通过$route.params获取参数。
通过上述机制,Vue Router 实现了单页应用的无刷新页面切换和组件动态渲染。






