- 前端路由實現(xiàn)
前端路由實現(xiàn)的簡要原理,以 hash 形式(也可以使用 History API 來處理)為例,當 url 的 hash 發(fā)生變化時,觸發(fā) hashchange 注冊的回調,回調中去進行不同的操作,進行不同的內容的展示。直接看代碼或許更直觀。
function Router() {
this.routes = {};
this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
this.routes[path] = callback || function(){};
};
Router.prototype.refresh = function() {
this.currentUrl = location.hash.slice(1) || '/';
this.routes[this.currentUrl]();
};
Router.prototype.init = function() {
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
window.Router = new Router();
window.Router.init();
- 上面路由系統(tǒng) Router 對象實現(xiàn),主要提供三個方法
init 監(jiān)聽瀏覽器 url hash 更新事件
route 存儲路由更新時的回調到回調數(shù)組routes中,回調函數(shù)將負責對頁面的更新
refresh 執(zhí)行當前url對應的回調函數(shù),更新頁面 - Router 調用方式以及呈現(xiàn)效果如下:點擊觸發(fā) url 的 hash 改變,并對應地更新內容(這里為 body 背景色)
<ul>
<li><a href="#/">turn white</a></li>
<li><a href="#/blue">turn blue</a></li>
<li><a href="#/green">turn green</a></li>
</ul>
var content = document.querySelector('body');
// change Page anything
function changeBgColor(color) {
content.style.backgroundColor = color;
}
Router.route('/', function() {
changeBgColor('white');
});
Router.route('/blue', function() {
changeBgColor('blue');
});
Router.route('/green', function() {
changeBgColor('green');
});
以上為一個前端路由的簡單實現(xiàn),下面是完整代碼,雖然簡單,但實際上很多路由系統(tǒng)的根基都立于此,其他路由系統(tǒng)主要是對自身使用的框架機制的進行配套及優(yōu)化,如與 react 配套的 react-router。
- 完整代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>router</title>
</head>
<body>
<ul>
<li><a href="#/">turn white</a></li>
<li><a href="#/blue">turn blue</a></li>
<li><a href="#/green">turn green</a></li>
</ul>
<script>
function Router() {
this.routes = {};
this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
this.routes[path] = callback || function(){};
};
Router.prototype.refresh = function() {
this.currentUrl = location.hash.slice(1) || '/';
this.routes[this.currentUrl]();
};
Router.prototype.init = function() {
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
window.Router = new Router();
window.Router.init();
var content = document.querySelector('body');
// change Page anything
function changeBgColor(color) {
content.style.backgroundColor = color;
}
Router.route('/', function() {
changeBgColor('white');
});
Router.route('/blue', function() {
changeBgColor('blue');
});
Router.route('/green', function() {
changeBgColor('green');
});
</script>
</body>
</html>