原生 js 如何进行监听路由的变化?
参考答案
hash 模式
window.addEventListener('hashchange', handler),location.hash 读取。
history 模式
popstate:只能捕获前进/后退(用户操作);pushState/replaceState不触发任何事件,需自行包装:
const raw = history.pushState;
history.pushState = function (...args) { raw.apply(this, args); handler(); };
- 新方案:
Navigation API的navigate事件(Chrome 支持); - 兜底:轮询
location.href变化(不推荐)。
路由库(Vue Router / React Router)本质都是包装 history + popstate 订阅。