hash
路由利用hash實現路由切換javascript
<html lang="en">
<head>
<style> #root{ height: 200px; border: 1px solid red; } </style>
</head>
<body>
<a href="#/a">跳轉到/a</a>
<a href="#/b">跳轉到/b</a>
<div id="root"></div>
<script> let container = document.getElementById('root'); window.addEventListener('hashchange',function (e) { console.log(e); container.innerHTML = `當前的路徑是${window.location.hash.slice(1)}`; }) </script>
</body>
</html>
複製代碼
hash
切換路由的時候回觸發hashchange
事件window.location.hash
能夠拿到當前頁面的hash
值Browser
路由利用
H5——API
實現路由切換css
history
對象提供了操做瀏覽器會話歷史的接口html
back
跳到上一個路徑,做用同瀏覽器的回退按鈕forward
跳到下一個路徑,做用同瀏覽器的前進按鈕go
跳到某個路徑
go(1) === forword()
,go(-1) === back()
;length
表示當前路徑隊列中存儲的路徑個數pushState
在當前路徑隊列中增長新的路徑,而且跳轉到新路徑;length + 1
history.pushState({name:'新的狀態'},'新的標題(已經廢棄)','/新的路徑')
replaceState
在當前的路徑隊列中用新的替換當前路徑;length
不變
pushState
<html lang="en">
<head>
<style> #root { height: 200px; border: 1px solid red; } </style>
</head>
<body>
<button onclick="push('/a')">/a</button>
<button onclick="push('/b')">/b</button>
<button onclick="push('/c')">/c</button>
<div id="root"></div>
<script> let container = document.getElementById('root'); /** * 監聽彈出狀態的事件(出棧操做) */ window.onpopstate = function (e) { console.log(e); container.innerHTML = e.state.to; } function push(to) { /** * pushState (入棧操做) * 三個參數 1.新的狀態對象 2.標題(已經廢棄) 3.跳轉到的路徑 */ window.history.pushState({ to }, null, to); } </script>
</body>
</html>
複製代碼
window.onpopstate
)window.onpushstate
事件,可是很遺憾,瀏覽器並無給咱們提供這個事件。pushState
&& 實現onpushstate
方法——實現點擊路由切換按鈕同時進行視圖切換let oldPushState = window.history.pushState; // 保存原有的pushState方法;
window.history.pushState = function(state,title,url){
onpushstate(state,title,url); // 調用咱們手寫的onpushstate切換視圖
oldPushState.call(window.history,state,title,url); // 調用原有的pushState方法實現路由切換
}
window.onpushstate = function(state,title,url){
container.innerHTML = state.to || url;
}
複製代碼
文章主要是從底層的角度剖析了單頁面應用路由的實現原理,三大框架的路由原理也是基於這個底層思想實現,後續會爲你們帶來
React-Router
的源碼解析;若是以爲寫的還能夠幫忙點個👍,😉小生將不勝感激🤘。java