单页应用通过前端路由实现无刷新切换,核心是Hash和History两种模式。1. Hash模式利用URL中#后的部分变化触发hashchange事件,兼容性好但URL不美观;2. History模式使用pushState和replaceState API操作浏览器历史记录,配合popstate事件监听,可实现干净的URL路径,需服务端配置fallback以避免404。两者选择取决于浏览器兼容性、URL美观需求及服务端支持情况,理解其原理有助于掌握Vue Router、React Router等框架路由机制。

单页应用(SPA)之所以能实现页面无刷新切换,核心在于前端路由。它通过监听 URL 的变化,在不重新请求服务器的情况下动态加载对应视图内容。前端路由主要有两种实现方式:Hash 模式和 History 模式。
Hash 模式利用 URL 中的 # 后面的部分(即 hash 值)来模拟路由跳转。浏览器不会将 hash 部分发送给服务器,因此改变 hash 不会触发页面刷新,同时还会触发 hashchange 事件。
特点:
手动实现示例:
立即学习“前端免费学习笔记(深入)”;
class HashRouter {
constructor() {
this.routes = {};
window.addEventListener('hashchange', () => {
const path = location.hash.slice(1) || '/';
this.routes[path] && this.routes[path]();
});
}
on(path, callback) {
this.routes[path] = callback;
}
push(path) {
location.hash = path;
}
}
<p>// 使用
const router = new HashRouter();
router.on('/', () => console.log('首页'));
router.on('/about', () => console.log('关于页'));
History 模式基于 HTML5 的 History API(如 pushState、replaceState)实现。它能使用真实的 URL 路径(如 /about),看起来更自然。
关键 API:
手动实现示例:
立即学习“前端免费学习笔记(深入)”;
class HistoryRouter {
constructor() {
this.routes = {};
window.addEventListener('popstate', (e) => {
const path = location.pathname;
this.routes[path] && this.routes[path](e.state);
});
}
on(path, callback) {
this.routes[path] = callback;
}
push(path, state = {}) {
history.pushState(state, '', path);
this.routes[path] && this.routes[path](state);
}
replace(path, state = {}) {
history.replaceState(state, '', path);
this.routes[path] && this.routes[path](state);
}
}
<p>// 使用
const router = new HistoryRouter();
router.on('/home', () => console.log('进入 home'));
router.push('/home');
选择哪种模式取决于项目需求和部署环境。
Hash 模式适用场景:
History 模式适用场景:
使用 History 模式时,服务端必须配置 fallback,确保所有前端路由路径都返回同一个 HTML 文件,否则直接访问会 404。
基本上就这些。理解前端路由的本质,有助于更好地掌握 Vue Router、React Router 等框架级路由工具的底层逻辑。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号