1. 前端路由的本质与演进历程
现代Web应用早已不再是通过点击超链接跳转页面的传统模式。当我们使用单页应用(SPA)时,页面内容动态更新而浏览器地址栏同步变化的技术,就是前端路由的魔法。这种无刷新跳转体验的背后,是浏览器History API与哈希(hash)两种模式的精妙配合。
早期的前端路由主要依赖location.hash实现。2011年HTML5 History API的出现彻底改变了游戏规则,pushState和replaceState方法允许开发者直接操作浏览器历史栈而不触发页面刷新。如今主流框架(React Router、Vue Router等)都采用这种模式作为默认方案,只有在检测到老旧浏览器时才会自动降级为hash模式。
关键认知:前端路由不是浏览器原生行为,而是通过JavaScript模拟的"假"路由。其核心价值在于保持单页应用体验的同时,提供符合用户预期的URL导航能力。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 两种路由模式的实现原理对比
2.1 Hash模式的工作原理
当我们在地址栏看到example.com/#/about这样的URL时,就是在使用hash路由。hash(即#后的部分)的变化不会导致浏览器向服务器发送请求,但会触发hashchange事件:
javascript复制window.addEventListener('hashchange', () => {
const currentHash = window.location.hash.substr(1);
renderComponentBasedOnRoute(currentHash);
});
实现一个基础的hash路由仅需不到50行代码:
javascript复制class HashRouter {
constructor(routes = []) {
this.routes = routes;
this.currentHash = '';
window.addEventListener('load', () => this.handleHashChange());
window.addEventListener('hashchange', () => this.handleHashChange());
}
handleHashChange() {
this.currentHash = window.location.hash.slice(1) || '/';
const matchedRoute = this.routes.find(route => route.path === this.currentHash);
matchedRoute?.component();
}
}
2.2 History模式的底层机制
History API提供了更优雅的解决方案。关键方法包括:
history.pushState(state, title, url):添加历史记录history.replaceState():替换当前历史记录popstate事件:响应前进/后退操作
典型实现方案:
javascript复制class HistoryRouter {
constructor(routes) {
this.routes = routes;
this.bindEvents();
this.init();
}
bindEvents() {
window.addEv
