🎙️前端路由的两种方式history和hash

365 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第28天,点击查看活动详情

🎈大家好,我是橙橙子,新人初来乍到,请多多关照~

📝小小的前端一枚,分享一些日常的学习和项目实战总结~

😜如果本文对你有帮助的话,帮忙点点赞呀!ღ( ´・ᴗ・` )比心~

vue的前端路由有两种模式:hash 模式和 history 模式,各有优缺点,我们一起看看吧~

hash 模式

hash 模式是把前端路由的路径用井号 # 拼接在真实 URL 后面的模式。当井号 # 后面的路径发生变化时,浏览器并不会重新发起请求,而是会触发 hashchange 事件。

举个栗子🌰

新建一个 hash.html 文件,我们利用 a 标签设置了两个路由导航,把 app 当做视图渲染容器,当切换路由的时候触发视图容器的更新。

<a href="#/a">A页面</a>
<a href="#/b">B页面</a>
<div id="app"></div>
<script>
  function render() {
    app.innerHTML = window.location.hash
  }
  window.addEventListener('hashchange', render)
  render()
</script>

hash 模式的优缺点

  • 优点:浏览器兼容性较好, 支持IE8
  • 缺点:路径在井号 # 后面,相对丑一点

history 模式

history API 是 H5 提供的新特性,允许开发者直接更改前端路由,即更新浏览器 URL 地址而不重新发起请求。

举个栗子🌰

新建一个 history.html

<a href="javascript:toA();">A页面</a>
<a href="javascript:toB();">B页面</a>
<div id="app"></div>
<script>
  function render() {
    app.innerHTML = window.location.pathname
  }
  function toA() {
    history.pushState({}, null, '/a')
    render()
  }
  function toB() {
    history.pushState({}, null, '/b')
    render()
  }
 window.addEventListener('popstate', render)
</script>

history API 提供了丰富的函数

history.replaceState({}, null, '/b') // 替换路由
history.pushState({}, null, '/a') // 路由压栈
history.back() // 返回
history.forward() // 前进
history.go(-2) // 后退2次

可以监听到 popstate 事件

  • 用户点击浏览器的前进和后退操作
  • 手动调用 history 的 backforward 和 go 方法

不能监听到:

  • history 的 pushState 和 replaceState方法

浏览器在刷新的时候,会按照路径发送真实的资源请求,如果这个路径是前端通过 history API 设置的 URL,那么在服务端往往不存在这个资源,于是就返回 404 了。如果后端资源不存在就返回 history.html 的内容。

所以在线上环境部署基于 history API 的单页面应用的时候,一定要后端配合支持才行,否则会出现大量的 404。以最常用的 Nginx 为例,只需要在配置的 location / 中增加下面一行:

try_files $uri /index.html;

history 模式的优缺点:

  • 优点:路径比较正规,没有井号 #
  • 缺点:兼容性不如 hash,且需要服务端支持,否则一刷新页面就404了