最近研究vue-router單頁轉跳而不向服務器請求的原理,vue
主要是HTML5 history以及hash的應用,支持history時使用history模式vue-router
下面詳細學習了一下經常使用的history相關的API跨域
經常使用API:瀏覽器
1.history.length:服務器
返回當前頁面所產生的歷史記錄個數,即在同一個瀏覽器tab下產生的歷史記錄;函數
2.history.pushState(state,title,URL):學習
向瀏覽器新增一條歷史記錄,可是不會刷新當前頁面(不會重載),其中state爲對象,能夠用做攜帶信息用,title:目前來看沒啥用通常爲空或null,URL:即要更改頁面的URL,且必須同源,不能跨域;spa
3.history.replaceState(state,title,URL):code
更改當前瀏覽器的歷史記錄,即把當前執行此代碼頁面的記錄給替換掉,參數與第二條相同;router
4.history.back()、history.forward()、history.go():
分別爲前進一個歷史,後退一個,history.go(Number),其中Number可正可負,即向前或向後若干個記錄
5.history.state:
返回當前頁面狀態參數,此參數通常由history.pushState(state,title,URL);以及history.replaceState(state,title,URL);附帶的state值,例子以下:
當前頁面爲http://example.com
history.pushState({a:1},null,"test1");//http://example.com/test1 history.state; //{a:1} history.pushState({b:2},null,"test2");//http://example.com/test2 history.state; //{b:2} history.back(); //http://example.com/test1 history.state; //{a:1} history.back(); //http://example.com history.state; //null
上面例子應該已經很明確的代表state的取值,即當前頁面的狀態值,沒有狀態值爲null;
6.history事件onpopstate:
window.onpopstate = function(e){ console.log(e.state); }
在history.back(),history.forward(),history.go()時觸發此事件,可是在history.pushState();history.replaceState();時並不會觸發此事件,事件內能夠獲取到state狀態值
由此能夠看出vue-router中push()、go()等函數的一些端倪,可是vue-router比這個要複雜,
history是其基礎之一