單頁應用 (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'} 物件)。pushState) 實現無 Hash 路由(需後端配合)。import() 對應模組。這個迷你路由器展示了前端路由核心原理:Hash 解析 → 正則匹配 → 參數提取 → 回調執行。代碼不足 50 行,適合學習原理或輕量專案直接使用。