如何用Javascript实现路由功能?

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

用 JavaScript 实现前端路由,核心是监听 URL 变化、解析路径、匹配规则、动态渲染对应内容——不依赖框架也能做到,关键是掌握 history.pushStatepopstate 事件和 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 或正则测试

实现简易 Router 类(可直接用)

封装成类更易复用,内部管理路由表、监听、跳转方法:

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) })

处理锚点与 404

真实项目中要兼顾边界情况:

  • 忽略 hash(如 #section1):只取 location.pathname,别用 location.href
  • 未匹配路径:加一个 '*' 通配符路由,显示 404 页面
  • 服务端配合:部署时确保所有路由都返回 index.html(否则直接访问 /admin 会 404)

基本上就这些。不复杂但容易忽略首次加载和 history 状态管理——写完记得测一下点击链接、浏览器前后按钮、直接输入 URL 这三种场景是否都正常。