js route 实现
路由实现的基本概念
在JavaScript中实现路由通常涉及监听URL变化并根据不同路径显示不同内容。前端路由有两种主要模式:Hash模式和History模式。
Hash模式路由实现
Hash模式利用URL中的#符号实现路由变化,不会触发页面刷新。

class HashRouter {
constructor() {
this.routes = {};
window.addEventListener('hashchange', this.load.bind(this));
}
addRoute(path, callback) {
this.routes[path] = callback;
}
load() {
const hash = window.location.hash.slice(1) || '/';
const callback = this.routes[hash];
if (callback) callback();
}
}
// 使用示例
const router = new HashRouter();
router.addRoute('/', () => console.log('Home Page'));
router.addRoute('/about', () => console.log('About Page'));
History模式路由实现
History模式使用HTML5 History API实现更干净的URL。

class HistoryRouter {
constructor() {
this.routes = {};
window.addEventListener('popstate', this.load.bind(this));
}
addRoute(path, callback) {
this.routes[path] = callback;
}
navigate(path) {
history.pushState({}, '', path);
this.load();
}
load() {
const path = window.location.pathname;
const callback = this.routes[path];
if (callback) callback();
}
}
// 使用示例
const router = new HistoryRouter();
router.addRoute('/', () => console.log('Home Page'));
router.addRoute('/about', () => console.log('About Page'));
动态路由处理
处理带参数的动态路由需要解析URL中的变量。
class DynamicRouter extends HistoryRouter {
load() {
const path = window.location.pathname;
// 匹配动态路由
for (const route in this.routes) {
const routeRegex = new RegExp('^' + route.replace(/:\w+/g, '([^/]+)') + '$');
const match = path.match(routeRegex);
if (match) {
const params = this.extractParams(route, match);
this.routes[route](params);
return;
}
}
console.error('Route not found');
}
extractParams(route, match) {
const paramNames = [...route.matchAll(/:(\w+)/g)].map(m => m[1]);
return paramNames.reduce((params, name, i) => {
params[name] = match[i+1];
return params;
}, {});
}
}
// 使用示例
const router = new DynamicRouter();
router.addRoute('/user/:id', (params) => console.log(`User ID: ${params.id}`));
路由守卫实现
添加路由守卫可以在导航前进行权限检查。
class GuardedRouter extends HistoryRouter {
constructor() {
super();
this.beforeHooks = [];
}
beforeEach(guard) {
this.beforeHooks.push(guard);
}
navigate(path) {
this.runGuards(path, () => {
super.navigate(path);
});
}
runGuards(path, next) {
let index = 0;
const runNextGuard = () => {
if (index < this.beforeHooks.length) {
this.beforeHooks[index++](path, runNextGuard);
} else {
next();
}
};
runNextGuard();
}
}
// 使用示例
const router = new GuardedRouter();
router.beforeEach((path, next) => {
console.log(`Checking access to ${path}`);
next();
});
这些实现展示了JavaScript中路由的核心概念,可以根据项目需求进行扩展或简化。实际项目中通常会使用现有的路由库如React Router或Vue Router,它们提供了更完善的功能和更好的开发体验。






