js route 实现
路由实现的基本方法
在JavaScript中实现路由功能通常涉及监听URL变化并根据路径渲染不同内容。常见方法包括原生API和第三方库。
监听URL变化
window.addEventListener('popstate', () => {
const path = window.location.pathname;
renderContent(path);
});
修改URL而不刷新页面
history.pushState({}, '', '/new-path');
基于Hash的路由实现
Hash路由利用URL中#后的部分实现无刷新跳转,兼容性较好。
初始化路由
function initRouter(routes) {
window.addEventListener('hashchange', () => {
const hash = window.location.hash.slice(1) || '/';
const route = routes[hash] || routes['*'];
route && route();
});
}
定义路由表
const routes = {
'/': () => renderHomePage(),
'/about': () => renderAboutPage(),
'*': () => renderNotFound()
};
基于History API的路由
现代SPA应用更推荐使用History API实现更干净的URL。
路由匹配逻辑

function matchRoute(path, routes) {
const routeKeys = Object.keys(routes);
const matchedKey = routeKeys.find(key => {
if (key.includes(':')) {
const regex = new RegExp(`^${key.replace(/:\w+/g, '([^/]+)')}$`);
return regex.test(path);
}
return key === path;
});
return matchedKey ? routes[matchedKey] : routes['*'];
}
动态参数处理
'/user/:id': (params) => {
console.log(`User ID: ${params.id}`);
}
第三方库集成
对于复杂应用,可考虑成熟的路由库:
React Router示例
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:id" element={<UserProfile />} />
</Routes>
</BrowserRouter>
Vue Router示例

const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHistory(),
routes
})
路由守卫实现
保护特定路由需要验证逻辑:
认证检查
function requireAuth(to, from, next) {
if (isLoggedIn()) next();
else next('/login');
}
路由配置
{
path: '/dashboard',
component: Dashboard,
beforeEnter: requireAuth
}
性能优化技巧
代码分割
const LazyComponent = React.lazy(() => import('./LazyComponent'));
预加载策略
router.beforeEach((to, from, next) => {
if (to.meta.preload) {
preloadComponent(to.component);
}
next();
});






