跳到主要内容

如何用 JS 实现 hash 路由

前端路由原理

  • vue-router 的路由模式
  • hash
  • H5 history

网页 url 组成部分

// http://localhost:8080/test/test.html?a=100#100
console.log(location.protocol) // http:
console.log(location.host) // localhost
console.log(location.port) // 8080
console.log(location.pathname) // /test/test.html
console.log(location.search) // ?a=100
console.log(location.hash) // #100

hash 的特点

  • hash 变化会触发网页跳转,即浏览器的前进,后端
  • hash 变化不会刷新页面,SPA 必需的特点
  • hash 永远不会提交到 server 端(前端自生自灭)

演示一下

<button id="btn">修改 hash</button>
<script>
// hash 变化,包含:
// a. JS 修改 url
// b. 手动修改 url 的 hash
// c. 浏览器前进、后退
window.onhashchange = (e) => {
console.log('old url', e.oldURL)
console.log('new url', e.newURL)
console.log('hash', location.hash)
}
// 页面初次加载,获取 hash
document.addEventListener('DOMContentLoaded', () => {
console.log('hash:', location.hash)
})
// JS 修改 url
document.getElementById('btn').addEventListener('click', () => {
location.href = '#/user'
})
</script>

以上一开始为空,点击一下触发 onhashchange 输出:

// 一开始为空,点击一下触发 onhashchange
// hash:
// old url http://localhost/test/test.html
// new url http://localhost/test/test.html#/user
// hash #/user