js原生实现vue路由
使用 History API 实现路由切换
通过 window.history.pushState 和 popstate 事件可以实现前端路由的无刷新跳转。创建一个路由对象管理路径与组件的映射关系。
class SimpleRouter {
constructor(routes) {
this.routes = routes;
this.currentComponent = null;
window.addEventListener('popstate', () => this.handleRouteChange());
}
handleRouteChange() {
const path = window.location.pathname;
const route = this.routes.find(r => r.path === path);
if (route) {
this.currentComponent = route.component;
this.render();
}
}
navigate(path) {
window.history.pushState({}, '', path);
this.handleRouteChange();
}
render() {
const app = document.getElementById('app');
app.innerHTML = '';
app.appendChild(this.currentComponent());
}
}
配置路由与组件映射
定义路由配置数组,每个路由对象包含路径和对应的组件渲染函数。

const routes = [
{
path: '/',
component: () => {
const div = document.createElement('div');
div.textContent = 'Home Page';
return div;
}
},
{
path: '/about',
component: () => {
const div = document.createElement('div');
div.textContent = 'About Page';
return div;
}
}
];
const router = new SimpleRouter(routes);
router.handleRouteChange(); // 初始化路由
实现导航链接
创建自定义的 <a> 标签,阻止默认跳转行为并使用路由的 navigate 方法。

document.querySelectorAll('a[data-router]').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
router.navigate(e.target.getAttribute('href'));
});
});
处理动态路由参数
通过正则表达式匹配动态路径,并提取参数传递给组件。
// 修改路由配置
{
path: '/user/:id',
component: (params) => {
const div = document.createElement('div');
div.textContent = `User ID: ${params.id}`;
return div;
}
}
// 修改路由类的handleRouteChange方法
handleRouteChange() {
const path = window.location.pathname;
const route = this.routes.find(r => {
const regex = new RegExp(`^${r.path.replace(/:\w+/g, '(\\w+)')}$`);
return regex.test(path);
});
if (route) {
const params = this.extractParams(route.path, path);
this.currentComponent = () => route.component(params);
this.render();
}
}
extractParams(routePath, actualPath) {
const params = {};
const routeParts = routePath.split('/');
const actualParts = actualPath.split('/');
routeParts.forEach((part, i) => {
if (part.startsWith(':')) {
params[part.slice(1)] = actualParts[i];
}
});
return params;
}
添加路由守卫功能
通过中间件机制实现路由跳转前的权限校验。
class SimpleRouter {
constructor(routes, guards = []) {
this.guards = guards;
// ...其他初始化代码
}
async navigate(path) {
let allowNavigation = true;
for (const guard of this.guards) {
if (!await guard(path)) {
allowNavigation = false;
break;
}
}
if (allowNavigation) {
window.history.pushState({}, '', path);
this.handleRouteChange();
}
}
}
// 使用示例
const authGuard = async (path) => {
if (path === '/admin' && !isLoggedIn()) {
return false;
}
return true;
};
const router = new SimpleRouter(routes, [authGuard]);






