前端路由
- hash
- history API
hash
hash 是什么
js
// http://127.0.0.1:8881/01-hash.html?a=100&b=20#/aaa/bbb
location.protocol // 'http:'
location.hostname // '127.0.0.1'
location.host // '127.0.0.1:8881'
location.port // '8881'
location.pathname // '/01-hash.html'
location.search // '?a=100&b=20'
location.hash // '#/aaa/bbb'hash 的特点,重要!!!
- 会触发页面跳转,即可后退、前进
- 但不会刷新页面,支持 SPA 必须的特性
- hash 不会被提交到 server 端(因此刷新页面也会命中当前页面,让前端根据 hash 处理路由)
url 中的 hash ,是不会发送给 server 端的。前端 onhashchange 拿到自行处理。
onhashchange 监听 hash 变化
js
// 页面初次加载,获取 hash
document.addEventListener('DOMContentLoaded', () => {
console.log('hash', location.hash)
})
// hash 变化,包括:
// a. JS 修改 url
// b. 手动修改 url 的 hash
// c. 浏览器前进、后退
window.onhashchange = (event) => {
console.log('old url', event.oldURL)
console.log('new url', event.newURL)
console.log('hash', location.hash)
}history API
常用的两个 API
- history.pushState
- window.onpopstate
页面刷新时,服务端要做处理。即无论什么 url 访问 server ,都要返回该页面。
需要 server 端配合,可参考 https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子
按照 url 规范,不同的 url 对应不同的资源,例如:
但是用了 SPA 的前端路由,就改变了这一规则,假如 github 用了的话:
- https://github.com/ 首页
- https://github.com/username/ 首页(前端处理路由)
- https://github.com/username/xxx/ 首页(前端处理路由)
所以,从开发者的实现角度来看,前端路由是一个违反规则的形式。 但是从不关心后端,只关心前端页面的用户,或者浏览器来看,更喜欢 pushState 这种方式。
如何选择?
- 内部系统或 to B 的管理系统,用 hash 。简单易用,对 url 规范没有要求。
- to C 的页面,用 history API ,对 url 规范和 SEO 要求较高。—— 但需要服务端配合
结合 vue-router
vue-router 和 react-router 的路由原理

讨论区
欢迎留下想法与补充