萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現簡易前端路由器:Hash 模式路由映射與啟動

前言

單頁應用 (SPA) 核心需求之一是根據 URL Hash 顯示不同視圖。本文實作一個輕量級前端路由器 wawa.Router,支援路由規則映射、參數擷取、預設路由處理。

核心代碼

var wawa = {};
wawa.Router = (function () {
    function Router() {}

    Router.prototype.setup = function (routemap, defaultFunc) {
        var that = this;
        this.routemap = [];
        this.defaultFunc = defaultFunc;
        for (var rule in routemap) {
            if (!routemap.hasOwnProperty(rule)) continue;
            this.routemap.push({
                rule: new RegExp(rule, 'i'), // 不區分大小寫
                func: routemap[rule]
            });
        }
    };

    Router.prototype.start = function () {
        var hash = location.hash; // 如 "#/list/cate/123"
        for (var i = 0; i < this.routemap.length; i++) {
            var route = this.routemap[i];
            var match = hash.match(route.rule);
            if (match) {
                // match[0] 為完整匹配,match[1...] 為捕獲組
                route.func.apply(window, match.slice(1));
                return;
            }
        }
        this.defaultFunc(); // 無匹配時執行預設
    };

    return Router;
})();

使用範例

var router = new wawa.Router();
router.setup({
    '#/list/(.*)/(.*)': function (cate, id) {
        console.log('列表頁', cate, id); // cate=分類, id=頁碼或ID
    },
    '#/show/(.*)': function (id) {
        console.log('詳情頁', id);
    }
}, function () {
    console.log('預設路由 (首頁)');
});
router.start();

// 頁面載入或 hash 變化時呼叫
window.addEventListener('hashchange', function () { router.start(); });
router.start(); // 初始化

關鍵點解析

  • 路由規則使用正則表達式,支援捕獲組 (.*) 擷取動態參數。
  • match.slice(1) 將捕獲組作為參數傳遞給處理函式。
  • apply(window, ...) 確保處理函式內 this 指向 window(可依需求調整)。
  • 監聽 hashchange 事件實現無刷新導航。

擴展建議

  • 加入 beforeEach/afterEach 鉤子(權限驗證、頁面過渡動畫)。
  • 支援命名參數(如 #/user/:id 解析為 {id: '123'} 物件)。
  • 整合 History API (pushState) 實現無 Hash 路由(需後端配合)。
  • 路由懶加載:動態 import() 對應模組。

總結

這個迷你路由器展示了前端路由核心原理:Hash 解析 → 正則匹配 → 參數提取 → 回調執行。代碼不足 50 行,適合學習原理或輕量專案直接使用。

copyright © 萬盛學電腦網 all rights reserved