前端路由核心是监听URL变化、解析路径、匹配规则并动态渲染,关键用history.pushState、popstate事件和路径解析逻辑,需手动触发首次匹配并处理404与服务端配置。

用 JavaScript 实现前端路由,核心是监听 URL 变化、解析路径、匹配规则、动态渲染对应内容——不依赖框架也能做到,关键是掌握 history.pushState、popstate 事件和 URL 解析逻辑。
单页应用(SPA)不能靠刷新跳转,得用 History API 操作路由状态:
history.pushState(state, title, url) 替换当前 URL(不触发刷新),比如 pushState(null, '', '/about')
window.addEventListener('popstate', handler) 捕获后退/前进操作popstate 不会触发页面初始加载)把 URL 路径(location.pathname)和预定义的路由表比对,支持静态路径和简单参数:
if (path === '/home') renderHome()
URLPattern(较新,兼容性注意)提取,例如 /user/:id → 匹配 /user/123,取到 id = '123'
{ '/': homeHandler, '/post/:id': postHandler },遍历时用 path.startsWith 或正则测试封装成类更易复用,内部管理路由表、监听、跳转方法:
立即学习“Java免费学习笔记(深入)”;
dmSOBC SHOP网店系统由北京时代胜腾信息技术有限公司(http://www.webzhan.com)历时6个月开发完成,本着简单实用的理念,商城在功能上摒弃了外在装饰的一些辅助功能,尽可能的精简各项模块开发,做到有用的才开发,网店V1.0.0版本开发完成后得到了很多用户的使用并获得了好评,公司立即对网店进行升级,其中包括修正客户提出的一些意见和建议,现对广大用户提供免费试用版本,如您在使用
0
<font size="2"><pre class="brush:php;toolbar:false;">class SimpleRouter {
constructor(routes) {
this.routes = routes;
this.init();
}
init() {
window.addEventListener('popstate', () => this.route());
this.route(); // 首次加载
}
route() {
const path = location.pathname;
const match = Object.keys(this.routes).find(key => {
const regex = ^${key.replace(/:(\w+)/g, '([^/]+)')}$;
return regex.test(path);
});
if (match) {
const args = path.match(new RegExp(^${match.replace(/:(\w+)/g, '([^/]+)')}$));
this.routes[match](args?.slice(1) || []);
} else {
this.routes['*']?.();
}
}
go(path) {
history.pushState(null, '', path);
this.route();
}
}使用:new SimpleRouter({ '/': renderHome, '/user/:id': ([id]) => renderUser(id) })
真实项目中要兼顾边界情况:
#section1):只取 location.pathname,别用 location.href
'*' 通配符路由,显示 404 页面基本上就这些。不复杂但容易忽略首次加载和 history 状态管理——写完记得测一下点击链接、浏览器前后按钮、直接输入 URL 这三种场景是否都正常。
以上就是如何用Javascript实现路由功能?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号