路由的用途:做H5的時候,可以把所有頁面寫在一張頁面裏面,通過路由,來顯示你點擊過後需要出現的頁面。
路由實現的原理:window綁定了監聽函數,當url的hash值發生變化的時候會觸發hashchange回調,在回調中進行不同的操作,馬上刷新頁面,從而顯示不同的頁面。
js代碼如下
// 創建一個 newRouter 類
class newRouter {
// 初始化路由信息
constructor() { //構造方法
this.routes = {};
this.currentUrl = '';
}
// 切割 hash,渲染頁面
refresh() {
this.currentUrl = location.hash.slice(1) || '/'; //location.hash獲得#/setting /this.currentUrl獲得/setting
this.routes[this.currentUrl] && this.routes[this.currentUrl](); //回調函數
}
// 初始化
init() { //加載或者路徑發生變化時 刷新構造函數 中的變量
window.addEventListener('load', this.refresh.bind(this), false); //加一個監聽函數,綁定this this指向這個類
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
// 傳入 URL 以及 根據 URL 對應的回調函數
route(path, callback = () => {}) {
this.routes[path] = callback;
}
}
// new 一個 Router 實例
window.Router = new newRouter();
// 路由實例初始化
window.Router.init();
Router.route('/setting', () => {
document.querySelector(".wrap").style.display="none";
document.querySelector(".settingWrap").style.display="block";
});
Router.route('/back', () => {
document.querySelector(".wrap").style.display="block";
document.querySelector(".settingWrap").style.display="none";
});
</script>
html
<a href="#/setting">點擊這個就切換路徑了</a> // 樣式是wrap
<a href="#/back">點擊這個就又切換路徑了</a> //樣式是settingWrap
但是這個路由寫在下面,不然style改變不了