js 实现路由
实现路由的基本方法
在 JavaScript 中实现路由通常涉及监听 URL 变化,并根据 URL 路径渲染不同的内容。以下是几种常见的方法:
基于 window.location 和 history API
监听 URL 变化可以通过 popstate 事件或手动解析 window.location 实现。history.pushState 和 history.replaceState 可以修改 URL 而不触发页面刷新。
window.addEventListener('popstate', () => {
const path = window.location.pathname;
renderContent(path);
});
function navigateTo(path) {
history.pushState({}, '', path);
renderContent(path);
}
function renderContent(path) {
const root = document.getElementById('root');
root.innerHTML = path === '/home' ? '<h1>Home</h1>' : '<h1>404</h1>';
}
基于 hash 路由
hash 路由通过监听 hashchange 事件实现,适用于不支持 history API 的旧浏览器。
window.addEventListener('hashchange', () => {
const hash = window.location.hash.substr(1);
renderContent(hash);
});
function navigateTo(path) {
window.location.hash = path;
}
function renderContent(path) {
const root = document.getElementById('root');
root.innerHTML = path === 'home' ? '<h1>Home</h1>' : '<h1>404</h1>';
}
使用第三方库
React Router
在 React 中,可以使用 react-router-dom 实现路由功能。
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="/home">Home</Link>
<Route path="/home" component={Home} />
</Router>
);
}
function Home() {
return <h1>Home</h1>;
}
Vue Router
在 Vue 中,可以通过 vue-router 实现路由。
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{ path: '/home', component: Home }
];
const router = new VueRouter({ routes });
new Vue({
router,
template: '<router-view></router-view>'
}).$mount('#app');
动态路由匹配
动态路由允许根据参数渲染不同内容,例如用户 ID 或产品名称。

React Router 动态路由
<Route path="/user/:id" component={User} />
function User({ match }) {
return <h1>User ID: {match.params.id}</h1>;
}
Vue Router 动态路由
const routes = [
{ path: '/user/:id', component: User }
];
function User() {
return <h1>User ID: {{ $route.params.id }}</h1>;
}
路由守卫
路由守卫用于在导航前后执行逻辑,例如权限验证或数据加载。
React Router 守卫
通过高阶组件或 useEffect 实现。

function PrivateRoute({ component: Component, ...rest }) {
const isAuthenticated = checkAuth();
return (
<Route
{...rest}
render={props =>
isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
}
/>
);
}
Vue Router 守卫
通过 beforeEach 钩子实现。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
嵌套路由
嵌套路由允许在父路由下定义子路由。
React Router 嵌套路由
<Route path="/dashboard" component={Dashboard}>
<Route path="/dashboard/profile" component={Profile} />
</Route>
Vue Router 嵌套路由
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'profile', component: Profile }
]
}
];
以上方法涵盖了从原生 JavaScript 到主流框架的路由实现,可以根据项目需求选择适合的方案。






