vue实现路由原理
Vue 路由实现原理
Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心原理基于前端路由技术,通过监听 URL 变化并动态渲染组件。
路由模式
Vue Router 支持两种路由模式:
-
Hash 模式:利用 URL 的 hash(
#)部分实现路由切换。例如http://example.com/#/home。
特点:兼容性好,无需服务器配置,但 URL 不够美观。 -
History 模式:基于 HTML5 History API(
pushState、replaceState)实现无#的路由。例如http://example.com/home。
特点:URL 更直观,但需服务器支持(避免 404 问题)。
核心实现机制
1. 路由注册与映射
通过 routes 配置定义路径与组件的映射关系。Vue Router 会解析配置并生成路由表。
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
2. 路由监听
- Hash 模式:监听
hashchange事件,当 URL 的 hash 变化时触发路由切换。 - History 模式:监听
popstate事件(用户点击后退/前进按钮时触发),并通过pushState/replaceState手动更新 URL。
3. 动态渲染
根据当前 URL 匹配路由表,找到对应组件并渲染到 <router-view> 占位符中。Vue Router 通过响应式机制确保视图与 URL 同步。
关键源码逻辑(简化版)
路由初始化
class VueRouter {
constructor(options) {
this.routes = options.routes;
this.mode = options.mode || 'hash';
this.history = this.mode === 'hash'
? new HashHistory(this)
: new BrowserHistory(this);
}
}
Hash 模式实现
class HashHistory {
constructor(router) {
window.addEventListener('hashchange', () => {
router.transitionTo(window.location.hash.slice(1));
});
}
}
History 模式实现
class BrowserHistory {
constructor(router) {
window.addEventListener('popstate', (e) => {
router.transitionTo(window.location.pathname);
});
}
push(path) {
window.history.pushState({}, '', path);
this.router.transitionTo(path);
}
}
路由守卫
Vue Router 提供导航守卫(如 beforeEach),用于在路由切换前后执行逻辑(如权限校验)。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
总结
- Vue Router 通过监听 URL 变化(Hash 或 History API)实现无刷新页面切换。
- 核心是路由表匹配与动态渲染,结合响应式机制保证视图更新。
- 扩展功能如路由守卫、懒加载等增强了灵活性与控制力。







