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

來源:互聯網
上載者:User

標籤:對象   location   turn   頁面   函數   pat   back   改變   hang   

說一下前端路由實現的簡要原理,以 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 背景色)

<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 anythingfunction changeBgColor(color) {    content.style.backgroundColor = color;}Router.route(‘/‘, function() {    changeBgColor(‘white‘);});Router.route(‘/blue‘, function() {    changeBgColor(‘blue‘);});Router.route(‘/green‘, function() {    changeBgColor(‘green‘);});

 

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.