隨著 ajax 的使用越來越廣泛,前端的頁面邏輯開始變得越來越復雜,特別是spa的興起,前端路由系統(tǒng)隨之開始流行。 從用戶的角度看,前端路由主要實現(xiàn)了兩個功能(使用ajax更新頁面狀態(tài)的情況下):
作為開發(fā)者,要實現(xiàn)這兩個功能,我們需要做到:
我們路由常用的hash模式和history模式實際上就是實現(xiàn)了上面的功能。 hash模式這里的 hash 就是指 url 尾巴后的 # 號以及后面的字符。這里的 # 和 css 里的 # 是一個意思。hash 也 稱作 錨點,本身是用來做頁面定位的,她可以使對應 id 的元素顯示在可視區(qū)域內。 由于 hash 值變化不會導致瀏覽器向服務器發(fā)出請求,而且 hash 改變會觸發(fā) hashchange 事件,瀏覽器的進后退也能對其進行控制,所以人們在 html5 的 history 出現(xiàn)前,基本都是使用 hash 來實現(xiàn)前端路由的。 使用到的api: 1 window.location.hash = 'qq' // 設置 url 的 hash,會在當前url后加上 '#qq' 2 3 var hash = window.location.hash // '#qq' 4 5 window.addEventListener('hashchange', function(){ 6 // 監(jiān)聽hash變化,點擊瀏覽器的前進后退會觸發(fā) 7 }) ? history模式已經有 hash 模式了,而且 hash 能兼容到IE8, history 只能兼容到 IE10,為什么還要搞個 history 呢?
相關API: 1 window.history.pushState(state, title, url) 2 // state:需要保存的數(shù)據(jù),這個數(shù)據(jù)在觸發(fā)popstate事件時,可以在event.state里獲取 3 // title:標題,基本沒用,一般傳 null 4 // url:設定新的歷史記錄的 url。新的 url 與當前 url 的 origin 必須是一樣的,否則會拋出錯誤。url可以是絕對路徑,也可以是相對路徑。 5 //如 當前url是 https://www.baidu.com/a/,執(zhí)行history.pushState(null, null, './qq/'),則變成 https://www.baidu.com/a/qq/, 6 //執(zhí)行history.pushState(null, null, '/qq/'),則變成 https://www.baidu.com/qq/ 7 8 window.history.replaceState(state, title, url) 9 // 與 pushState 基本相同,但她是修改當前歷史記錄,而 pushState 是創(chuàng)建新的歷史記錄 10 11 window.addEventListener("popstate", function() { 12 // 監(jiān)聽瀏覽器前進后退事件,pushState 與 replaceState 方法不會觸發(fā) 13 }); 14 15 window.history.back() // 后退 16 window.history.forward() // 前進 17 window.history.go(1) // 前進一步,-2為后退兩步,window.history.lengthk可以查看當前歷史堆棧中頁面的數(shù)量 ? history 模式改變 url 的方式會導致瀏覽器向服務器發(fā)送請求,這不是我們想看到的,我們需要在服務器端做處理:如果匹配不到任何靜態(tài)資源,則應該始終返回同一個 html 頁面。 來源:https://www./content-4-625201.html |
|