vue路由实现原理hash
Vue 路由 Hash 模式的实现原理
Vue Router 的 Hash 模式利用 URL 中的 hash(#)部分来实现前端路由,无需服务器端配置。其核心原理是通过监听 hashchange 事件和操作 window.location.hash 来实现路由切换。
Hash 模式的特点
- URL 中 hash 的变化不会触发页面刷新。
- hash 值的变化会触发
hashchange事件。 - hash 部分不会被包含在 HTTP 请求中,完全由前端处理。
实现机制
监听 hash 变化
通过 window.addEventListener('hashchange', callback) 监听 URL 中 hash 的变化,并在回调函数中根据当前 hash 更新视图。
window.addEventListener('hashchange', () => {
const currentHash = window.location.hash.slice(1) || '/';
// 根据 currentHash 匹配路由并渲染组件
});
修改 hash
通过直接赋值 window.location.hash 或调用 history.pushState/history.replaceState 修改 hash,触发路由跳转。
// 跳转到 /about
window.location.hash = '/about';
// 或使用 pushState(兼容性更好)
history.pushState(null, null, '#/about');
Vue Router 的具体实现
Vue Router 在 Hash 模式下封装了以下逻辑:
-
初始化路由
- 解析初始 URL 的 hash 部分,匹配对应的路由配置。
- 渲染匹配的组件。
-
路由跳转
- 通过
router.push或router.replace触发 hash 变化。 - 内部调用
window.location.hash或history.pushState。
- 通过
-
事件监听
- 监听
hashchange事件,响应 hash 变化。 - 在事件回调中更新当前路由状态并重新渲染组件。
- 监听
简单实现示例
以下是一个简化的 Hash 路由实现:
class HashRouter {
constructor(routes) {
this.routes = routes;
this.currentHash = '';
window.addEventListener('hashchange', this.handleHashChange.bind(this));
window.addEventListener('load', this.handleHashChange.bind(this));
}
handleHashChange() {
this.currentHash = window.location.hash.slice(1) || '/';
const route = this.routes.find(route => route.path === this.currentHash);
if (route) {
// 渲染对应的组件
document.getElementById('app').innerHTML = route.component;
}
}
push(path) {
window.location.hash = path;
}
}
// 使用示例
const router = new HashRouter([
{ path: '/', component: '<div>Home</div>' },
{ path: '/about', component: '<div>About</div>' }
]);
总结
Hash 模式通过操作和监听 URL 的 hash 部分实现路由切换,无需后端支持,兼容性好,适合纯静态部署的场景。Vue Router 在此基础上封装了更完善的 API 和功能,如动态路由、导航守卫等。







