路由原理

路由原理
hash路由(核心api:hashchange事件)
利用a标签,并阻止默认事件。通过hashchange
事件监听hash值的变化,替换掉目标区域的html内容
1 | <h1>hash 路由</h1> |
1 | const $user = document.querySelector('#user') |
history路由(核心api:pushState/replaceState、popstate)
使用点击事件,将对应的名称通过pushState
/ replaceState
方法添加到浏览器history对象中,并在此时根据模块名称替换掉目标区域的html内容。随后,当浏览器发生后退、前进的行为时,可以通过popstate
事件监听到location.pathname,最后再做更新。

1 | <h1>history 路由</h1> |
1 | const $user = document.querySelector('#user') |
onpopstate
事件只能监听到由浏览器触发的历史记录变化,例如点击浏览器的==前进==或==后退==按钮,或者调用 history.back()
或 history.forward()
方法。
如果你在 JavaScript 中调用 history.pushState()
或 history.replaceState()
方法来修改浏览器的历史记录,那么不会触发 onpopstate
事件。
因此,如果你想要在调用 pushState()
或 replaceState()
方法后立即获取路由变化,可以在调用这两个方法后手动触发 popstate
事件,例如
1 | history.pushState({}, '', '/new-path'); |
在上面的代码中,我们先调用 pushState()
方法来修改浏览器的历史记录,并修改当前页面的 URL 为 /new-path
。然后,手动触发 popstate
事件,这会立即触发绑定在 window.onpopstate
上的事件处理函数,并获取到新的路由信息
- Post title: 路由原理
- Create time: 2021-08-11 13:15:00
- Post link: 2021/08/11/路由原理/
- Copyright notice: All articles in this blog are licensed under BY-NC-SA unless stating additionally.
Comments