原生JS實現一個簡單的前端路由(原理)

說一下前端路由實現的簡要原理,以 hash 形式(也可使用 History API 來處理)爲例,前端

當 url 的 hash 發生變化時,觸發 hashchange 註冊的回調,回調中去進行不一樣的操做,進行不一樣的內容的展現。數組

直接看代碼或許更直觀。瀏覽器

 1 function Router() {
 2     this.routes = {};
 3     this.currentUrl = '';
 4 }
 5 Router.prototype.route = function(path, callback) {
 6     this.routes[path] = callback || function(){};
 7 };
 8 Router.prototype.refresh = function() {
 9     this.currentUrl = location.hash.slice(1) || '/';
10     this.routes[this.currentUrl]();
11 };
12 Router.prototype.init = function() {
13     window.addEventListener('load', this.refresh.bind(this), false);
14     window.addEventListener('hashchange', this.refresh.bind(this), false);
15 }
16 window.Router = new Router();
17 window.Router.init();

上面路由系統 Router 對象實現,主要提供三個方法函數

  • init 監聽瀏覽器 url hash 更新事件
  • route 存儲路由更新時的回調到回調數組routes中,回調函數將負責對頁面的更新
  • refresh 執行當前url對應的回調函數,更新頁面

Router 調用方式以及呈現效果以下:點擊觸發 url 的 hash 改變,並對應地更新內容(這裏爲 body 背景色)this

<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');
});

 

相關文章
相關標籤/搜索