← 返回完整题库
JavaScript中等

原生 js 如何进行监听路由的变化?

参考答案

hash 模式

window.addEventListener('hashchange', handler),location.hash 读取。

history 模式

  1. popstate:只能捕获前进/后退(用户操作);
  2. pushState/replaceState 不触发任何事件,需自行包装:
const raw = history.pushState;
history.pushState = function (...args) { raw.apply(this, args); handler(); };
  1. 新方案:Navigation API 的 navigate 事件(Chrome 支持);
  2. 兜底:轮询 location.href 变化(不推荐)。

路由库(Vue Router / React Router)本质都是包装 history + popstate 订阅。

本题来自 计算机知识面试题库,共 921 道题。