使用js实现hash路由和h5 history 路由

782 阅读1分钟

使用js实现hash路由和h5 history 路由

先导语

今天我们将学习如何使用js来实现hash路由和h5 history 路由,并通过这个demo来学习前端路由的原理。

hash路由

hash 路由的特点:

  1. hash 变化会触发网页跳转
  2. hash 变化后网页不会刷新
  3. hash变化不会同步到server端

代码演示:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>hash test</title>
</head>
<body>
   <p>hash test</p>
   <button id="btn1">修改 hash</button>

   <script>
       // 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)
       }

       // 页面初次加载,获取 hash
       document.addEventListener('DOMContentLoaded', () => {
           console.log('hash:', location.hash)
       })

       // JS 修改 url
       document.getElementById('btn1').addEventListener('click', () => {
           location.href = '#/user'
       })
   </script>
</body>
</html>

js实现hash 路由的关键有两点:

  1. 监听hash的变化(window.onhashchange
  2. 手动修改url

h5 history路由

h5 history路由特点:

  1. 使用url路由规范,但跳转时不刷新页面
  2. 用到的API:history.pushStatewindow.onpopState

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>history API test</title>
</head>
<body>
    <p>history API test</p>
    <button id="btn1">修改 url</button>

    <script>
        // 页面初次加载,获取 path
        document.addEventListener('DOMContentLoaded', () => {
            console.log('load', location.pathname)
        })

        // 打开一个新的路由
        // 用 pushState 方式,浏览器不会刷新页面
        document.getElementById('btn1').addEventListener('click', () => {
            const state = { name: 'page1' }
            console.log('切换路由到', 'page1')
            history.pushState(state, '', 'page1') 
        })

        // 监听浏览器前进、后退
        window.onpopstate = (event) => { 
            console.log('onpopstate', event.state, location.pathname)
        }
    </script>
</body>
</html>

结束语

通过今天的学习,让我更加深刻的理解了前端路由是如何实现的。那么,下次见。好好学习,天天向上!

image.png