js原生实现vue路由
原生 JavaScript 实现 Vue 路由的核心逻辑
通过监听 URL 变化并动态渲染对应组件,可以实现类似 Vue Router 的功能。以下是关键实现步骤:
路由配置与初始化
定义路由配置对象,包含路径与组件的映射关系:
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/contact', component: Contact }
];
创建路由实例并初始化当前路由:
class Router {
constructor(routes) {
this.routes = routes;
this.currentRoute = null;
this.init();
}
}
监听 URL 变化
通过 popstate 事件监听浏览器前进/后退操作:
window.addEventListener('popstate', () => {
this.handleRouteChange();
});
手动触发路由变化时使用 pushState:
navigateTo(path) {
history.pushState({}, '', path);
this.handleRouteChange();
}
路由匹配与渲染
根据当前路径匹配对应组件:
matchRoute(path) {
return this.routes.find(route => route.path === path) ||
this.routes.find(route => route.path === '*');
}
渲染匹配到的组件:
handleRouteChange() {
const path = window.location.pathname;
this.currentRoute = this.matchRoute(path);
this.renderComponent();
}
renderComponent() {
const app = document.getElementById('app');
app.innerHTML = '';
new this.currentRoute.component().mount(app);
}
组件基类实现
定义基础组件类支持挂载逻辑:
class BaseComponent {
constructor() {
this.state = {};
}
mount(container) {
this.container = container;
this.render();
}
render() {
this.container.innerHTML = this.template();
}
template() {
return '';
}
}
示例组件实现:
class Home extends BaseComponent {
template() {
return `<h1>Home Page</h1>`;
}
}
路由链接组件
创建 <router-link> 的自定义实现:
class RouterLink extends HTMLElement {
connectedCallback() {
this.addEventListener('click', e => {
e.preventDefault();
router.navigateTo(this.getAttribute('to'));
});
}
}
customElements.define('router-link', RouterLink);
完整使用示例
初始化路由并挂载到 DOM:
const router = new Router(routes);
document.addEventListener('DOMContentLoaded', () => {
router.handleRouteChange();
});
HTML 中使用路由链接:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<div id="app"></div>
注意事项
- 需要处理 404 情况,可通过添加通配符路由
{ path: '*', component: NotFound } - 考虑添加路由守卫逻辑,在
handleRouteChange中加入验证钩子 - 复杂项目建议直接使用 Vue Router,此方案适用于学习原理或简单场景
这种实现省略了嵌套路由、懒加载等高级特性,但展示了前端路由的核心机制:URL 变化触发视图更新。







