前端路由之——History

前面我們講了前端路由之——hash的方法,今天我們來討論一下前端路由的另一種方式——History ヽ(✿゚▽゚)ノ

沒有看上一篇文章的小夥伴可以返回查看我們的歷史文章~~

首先我們來說一下這個history是個啥嘞 ?

js的history對象


  • window.history 表示window對象的歷史記錄

       1.window.history.back(),後退
    
      2.window.history.forward(),前進
    
      3.window.history.go(num),前進或後退指定數量歷史記錄
    
  • history.pushState() 方法向瀏覽器歷史添加了一個狀態。

      pushState()方法帶有三個參數:一個狀態對象、一個標題(現在被忽略了)以及一個可選的URL地址
      
      history.pushState(state, title, url);
    
  • window.history.replaceState(),修改當前的 history 實體。

       history.replaceState方法的參數與pushState方法一模一樣,不同之處在於replaceState()方法會修改當前歷史記錄條目而並非創建新的條目
    
  • popstate 事件,history 實體改變時觸發的事件。

  • window.history.state,會獲得 history 實體中的 state 對象。

上面介紹的 pushStatereplaceState是一個HTML5的新接口,他們的作用非常大,可以做到改變網址卻不需要刷新頁面,下面我們來詳細瞭解一下 ~~

詳細瞭解


pushState方法

接受三個參數,依次爲:

state:一個與指定網址相關的狀態對象,popstate事件觸發時,該對象會傳入回調函數。如果不需要這個對象,此處可以填null。

title:新頁面的標題,但是所有瀏覽器目前都忽略這個值,因此這裏可以填null。

url:新的網址,必須與當前頁面處在同一個域。瀏覽器的地址欄將顯示這個網址。

最常用的方法:window.history.pushState(null,null,'download?id=1');

完整使用:var oState= {title: '下載' };window.history.pushState(oState, '下載', 'download?id=1');

replaceState方法

和pushState原理一樣使用也一樣:

最常用的方法:window.history.replaceState(null,null,'download?id=1');

完整使用:var oState= {title: '下載' };window.history.replaceState(oState, '下載', 'download?id=1');

  • 特點:replaceState不會加入到歷史記錄裏面,用history.go(-1)會跳過當前頁面相當於是history.go(-2)。

栗子來了~


<!DOCTYPE HTML>
<!-- this starts off as http://example.com/line?x=5 -->
<title>Line Game - 5</title>
<p>You are at coordinate <span id="coord">5</span> on the line.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
 <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
 var currentPage = 5; // prefilled by server!!!!
 function go(d) {
     setupPage(currentPage + d);
     history.pushState(currentPage, document.title, '?x=' + currentPage);
 }
 onpopstate = function(event) {
     setupPage(event.state);
 }
 function setupPage(page) {
     currentPage = page;
     document.title = 'Line Game - ' + currentPage;
     document.getElementById('coord').textContent = currentPage;
     document.links[0].href = '?x=' + (currentPage+1);
     document.links[0].textContent = 'Advance to ' + (currentPage+1);
     document.links[1].href = '?x=' + (currentPage-1);
     document.links[1].textContent = 'retreat to ' + (currentPage-1);
 }
</script>

這是一個別人寫的栗子,我們點擊 Advance to ? 對應的 url 與模版都會 +1,反之點擊 retreat to ? 就會都 -1,這就滿足了 url 與模版視圖同時變化的需求 (ง •_•)ง ~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章