layui下有一款开源的路由组件layrouter,支持Hash监听,并回调实现单页面应用,但缺陷就是不支持参数,比如/admin/home/index,如果/admin/home/index?id=1,就会找不到该路由,基于此缺陷,改造并优化其代码,支持正则匹配路由。
注册路由
layrouter.register('/admin/user/center', { Url: '/admin/user/center' }, function (url, menu) {
loadView(url, menu);
});
注册正则表达式匹配路由
layrouter.register('^(/admin/keyvalue/index\\?id=)\\d+$', { Url: '/admin/keyvalue/index' }, function (url, menu) {
loadView(url, menu);
});
完整改造后的代码
layui.define([], function (exports) {
var layrouter = {
version: '1.0.0',
// 关键词
key: '',
// 路由表
routes: [],
// 当前 hash
currentHash: '',
// 注册路由
register: function (hash, data, callback) {
var that = this;
if (!hash) {
return;
}
hash = hash.toLowerCase();
// 给不同的 hash 设置不同的回调函数
if (typeof hash == 'string') {
that.routes[hash] = { data: data, func: function (url) { callback(url, data); } || function () { } };
} else if (hash instanceof Array) {
// 路由数组
for (var i in hash) {
that.register.apply(that, [].concat(hash[i]).concat({ data: data, func: function (url) { callback(url, data); } || function () { } }));
}
}
return that;
},
go: function (hash) {
var that = this;
window.location.hash = '#'.concat(that.key).concat(hash || '');
return that;
},
// 刷新
refresh: function () {
var that = this;
// 获取相应的 hash 值
//console.log(location.hash);
//console.log(location.hash.slice(1));
// 如果存在 hash 则获取, 否则为 /
that.currentHash = location.hash.slice(1) || '/';
if (!that.currentHash) {
that.replace('#/');
return;
}
that.currentHash = that.currentHash.toLowerCase();
// 根据当前 hash 调用对应的回调函数
var route = that.getRoute(that.currentHash);
if (route) {
route.func(that.currentHash);
return
}
},
// 初始化
init: function (options) {
var that = this;
if (!options) options = {};
// 使用自定义关键词
that.key = options.key || that.key;
window.addEventListener('load', that.refresh.bind(that), false);
window.addEventListener('hashchange', that.refresh.bind(that), false);
return that;
},
// Removes the current page from the session history and navigates to the given URL.
replace: function (url) {
window.location.replace(url);
},
// Navigate to the given URL.
href: function (url) {
window.location.href = url;
},
// Reloads the current page.
reload: function () {
window.location.reload();
},
getRoute: function (key) {
var that = this;
// 根据当前 hash 调用对应的回调函数
var route = that.routes[key];
if (route) {
return route;
}
//如果不存在路由,验证正则匹配
for (var hash in that.routes) {
if (new RegExp(hash, 'ig').test(key) == true) {
return that.routes[hash];
}
}
return null;
}
};
exports('layrouter', layrouter);
});
最后附上原作者的开源地址:
https://gitee.com/taadis/layrouter