前端路由的原理和實現

如今基本都是單頁面應用,如今單頁面應用可以模擬多頁面應用的效果,歸功於其前端路由機制。如今前端路由有兩種形式:css

Hash模式

如: xxx.xx.com/#/hash, 這種方式能夠實現刷新跳轉,不須要後端進行配合,主要是得益於haschange事件,當錨點哈希改變時,就會調用haschange函數,html

haschange模擬實現

(function(window) {
  // 若是瀏覽器原生支持該事件,則退出  
 if ( "onhashchange" in window.document.body ) { return; }
 var location = window.location,
 oldURL = location.href,
 oldHash = location.hash;
 // 每隔100ms檢測一下location.hash是否發生變化
 setInterval(function() {
    var newURL = location.href,
    newHash = location.hash;
    // 若是hash發生了變化,且綁定了處理函數...
    if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
    // execute the handler
      window.onhashchange({
        type: "hashchange",
        oldURL: oldURL,
        newURL: newURL
      });

      oldURL = newURL;
      oldHash = newHash;
    }
  }, 100);
})(window);
複製代碼

例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <ul>
       <li><a href="#/css">css</a></li>
       <li><a href="#/js">js</a></li>
       <li><a href="#/node">node</a></li>
   </ul>
   <div class="wrapper">
       當前選擇的是:<span></span>
   </div>
</body>
<script>
    window.onhashchange = function (e) {
        console.log(e);
        document.querySelector('.wrapper span').innerText = location.hash.split('/')[1]
    }
</script>
</html>
複製代碼

H5模式

如:xxx.xx.com/hash 這種模式須要後端路由配合使用。HTML5的History API爲瀏覽器的全局history對象增長的擴展方法。通常用來解決ajax請求沒法經過回退按鈕回到請求前狀態的問題前端

在HTML4中,已經支持window.history對象來控制頁面歷史記錄跳轉,經常使用的方法包括:node

  • history.forward(); //在歷史記錄中前進一步
  • history.back(); //在歷史記錄中後退一步
  • history.go(n): //在歷史記錄中跳轉n步驟,n=0爲刷新本頁,n=-1爲後退一頁。

在HTML5中,window.history對象獲得了擴展,新增的API包括:ajax

  • history.pushState(data[,title][,url]);//向歷史記錄中追加一條記錄
  • history.replaceState(data[,title][,url]);//替換當前頁在歷史記錄中的信息。
  • history.state;//是一個屬性,能夠獲得當前頁的state信息。
  • window.onpopstate;//是一個事件,在點擊瀏覽器後退按鈕或js調用forward()、back()、go()時觸發。監聽函數中可傳入一個event對象,event.state即爲經過pushState()或replaceState()方法傳入的data參數。注意調用pushState和replaceState不會觸發onpopstate事件
history.pushState({page: 1}, null, '?page=1');
    history.pushState({page: 2}, null, '?page=2');

    history.back(); //瀏覽器後退

    window.addEventListener('popstate', function(e) {
        //在popstate事件觸發後,事件對象event保存了當前瀏覽器歷史記錄的狀態.
        //e.state保存了pushState添加的state的引用
        console.log(e.state);  //輸出 {page: 1}
    });
複製代碼

相關文章
相關標籤/搜索