vue SPA设计 history hash

房东的猫 提交于 2019-12-04 11:50:45
<body>
  <h3>Histort api</h3>
  <a class="api a">a,html</a>
  <a class="api b">b,html</a>

  <script>
    //注册路由
    document.querySelectorAll('.api').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        let link = item.textContent;
        window.history.pushState({name: 'api'},link,link)
      }, false)
    });

    //监听路由
    window.addEventListener('popstate', (e) => {
      console.log({
        location: location.href,
        state: e.state
      });
    }, false)
  </script>

  <p>------------------</p>

  <h3>Hash</h3>
  <a class="hash a">#a.html</a>
  <a class="hash b">#b.html</a>

  <script>
    //注册路由
    document.querySelectorAll('.hash').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        let link = item.textContent;
        location.hash=link;
      }, false)
    });

    //监听路由
    window.addEventListener('hashchange', (e) => {
      console.log({
        location: location.href,
        hash: location.hash
      });
    }, false)
  </script> 
</body>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!