# hash模式和history模式基本原理

  • hash模式监听hashchange
  • history模式,监听popstate,调用history.pushState()或history.replaceState()不会触发popstate,所以需要手动触发onPopState

<body>
  <ul>
    <li><a href="#/home">home</a></li>
    <li><a href="#/about">about</a></li>
  </ul>
  <div id="routeView"></div>
  <script>
    window.addEventListener('DOMContentLoaded', onLoad)
    window.addEventListener('hashchange', onHashChange)
    var routeView = null
    function onLoad() {
      routeView = document.querySelector('#routeView')
      onHashChange()
    }
    function onHashChange() {
      const hash = window.location.hash
      switch(hash) {
        case '#/home':
          routeView.innerHTML = 'home';
          break;
        case '#/about':
          routeView.innerHTML = 'about';
          break;
          default:
          routeView.innerHTML = '默认';
      }
    }
  </script>
</body>

<body>
  <ul>
    <li><a href="/home">home</a></li>
    <li><a href="/about">about</a></li>
  </ul>
  <div id="routeView"></div>
  <script>
    var routeView = null
    window.addEventListener('DOMContentLoaded', onload)
    window.addEventListener('popstate', onPopState)
    function onload(){
      routeView = document.querySelector('#routeView')
      onPopState()
      var links = document.querySelectorAll('a[href]')
      links.forEach(el => {
        el.addEventListener('click', function(e) {
          e.preventDefault()
          console.log("el.getAttribute('href')", el.getAttribute('href'))
          history.pushState(null, '', el.getAttribute('href'))
          onPopState()
        })
      })
    }
    function onPopState() {
      switch(location.pathname) {
        case '/home':
        routeView.innerHTML = 'home'
        break;
        case '/about':
        routeView.innerHTML = 'about'
        break;
        default:
        routeView.innerHTML = '默认'
      }
    }
  </script>
</body>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69