js实现路由
js实现路由的方法
在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法:
使用原生JavaScript实现路由
通过监听window.onhashchange事件来实现基于哈希的路由:
window.onhashchange = function() {
const hash = window.location.hash.substring(1);
handleRoute(hash);
};
function handleRoute(route) {
switch(route) {
case 'home':
document.getElementById('content').innerHTML = '<h1>Home Page</h1>';
break;
case 'about':
document.getElementById('content').innerHTML = '<h1>About Page</h1>';
break;
default:
document.getElementById('content').innerHTML = '<h1>404 Not Found</h1>';
}
}
// 初始加载
window.onload = function() {
const initialRoute = window.location.hash.substring(1) || 'home';
handleRoute(initialRoute);
};
使用History API实现更现代的路由
HTML5 History API提供了更强大的路由控制能力:
function navigateTo(path) {
window.history.pushState({}, path, window.location.origin + path);
handleRoute(path);
}
window.onpopstate = function(event) {
handleRoute(window.location.pathname);
};
function handleRoute(path) {
switch(path) {
case '/home':
document.getElementById('content').innerHTML = '<h1>Home Page</h1>';
break;
case '/about':
document.getElementById('content').innerHTML = '<h1>About Page</h1>';
break;
default:
document.getElementById('content').innerHTML = '<h1>404 Not Found</h1>';
}
}
// 初始加载
window.onload = function() {
const initialPath = window.location.pathname || '/home';
handleRoute(initialPath);
};
使用第三方路由库
对于更复杂的应用,可以考虑使用成熟的第三方路由库:
- React Router (用于React应用)
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() { return (
); } ```- Vue Router (用于Vue应用)
const routes = [ { path: '/home', component: Home }, { path: '/about', component: About } ]
const router = new VueRouter({ routes })
new Vue({ router }).$mount('#app')
#### 实现一个简单的路由类
可以创建一个简单的路由类来管理应用路由:
```javascript
class Router {
constructor(routes) {
this.routes = routes;
this._loadInitialRoute();
this._listenToLinks();
}
_loadInitialRoute() {
const path = window.location.pathname;
this._handleRoute(path);
}
_listenToLinks() {
document.addEventListener('click', (e) => {
if (e.target.matches('[data-link]')) {
e.preventDefault();
const path = e.target.getAttribute('href');
this.navigateTo(path);
}
});
}
navigateTo(path) {
window.history.pushState({}, '', path);
this._handleRoute(path);
}
_handleRoute(path) {
const matchedRoute = this.routes.find(route => route.path === path);
if (matchedRoute) {
matchedRoute.component();
} else {
console.error('Route not found');
}
}
}
// 使用示例
const routes = [
{ path: '/home', component: () => console.log('Home Page') },
{ path: '/about', component: () => console.log('About Page') }
];
const router = new Router(routes);
这些方法提供了从简单到复杂的路由实现方案,可以根据项目需求选择适合的方式。对于单页应用(SPA),推荐使用History API或成熟的第三方路由库。







