原生js实现组件化
原生 JavaScript 实现组件化
原生 JavaScript 可以通过模块化、自定义元素、事件驱动等方式实现组件化。以下是几种常见的方法:
基于类的组件化
使用 ES6 的类(Class)封装组件逻辑,通过实例化类来创建组件。
class ButtonComponent {
constructor(text, onClick) {
this.text = text;
this.onClick = onClick;
}
render() {
const button = document.createElement('button');
button.textContent = this.text;
button.addEventListener('click', this.onClick);
return button;
}
}
// 使用组件
const button = new ButtonComponent('Click me', () => {
console.log('Button clicked!');
});
document.body.appendChild(button.render());
基于自定义元素(Web Components)
使用 Custom Elements API 定义新的 HTML 元素,实现组件化。
class CustomButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
button {
background: blue;
color: white;
border: none;
padding: 8px 16px;
cursor: pointer;
}
</style>
<button><slot></slot></button>
`;
}
}
// 注册自定义元素
customElements.define('custom-button', CustomButton);
// 使用组件
const button = document.createElement('custom-button');
button.textContent = 'Click me';
document.body.appendChild(button);
基于事件驱动的组件通信
通过自定义事件实现组件间的通信。
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
}
emit(event, ...args) {
if (this.events[event]) {
this.events[event].forEach(listener => listener(...args));
}
}
}
// 组件A
class ComponentA extends EventEmitter {
constructor() {
super();
this.render();
}
render() {
const button = document.createElement('button');
button.textContent = 'Emit Event';
button.addEventListener('click', () => {
this.emit('customEvent', 'Hello from ComponentA');
});
document.body.appendChild(button);
}
}
// 组件B
class ComponentB extends EventEmitter {
constructor() {
super();
this.on('customEvent', this.handleEvent);
}
handleEvent(data) {
console.log('Received:', data);
}
}
// 使用组件
const componentA = new ComponentA();
const componentB = new ComponentB();
componentA.on('customEvent', data => {
console.log('ComponentB received:', data);
});
基于闭包的模块化
使用闭包和 IIFE(立即执行函数)封装组件逻辑,避免全局污染。
const CounterComponent = (() => {
let count = 0;
const increment = () => {
count++;
updateDisplay();
};
const updateDisplay = () => {
const display = document.getElementById('counter-display');
if (display) {
display.textContent = count;
}
};
const render = () => {
const container = document.createElement('div');
container.innerHTML = `
<div id="counter-display">${count}</div>
<button id="counter-button">Increment</button>
`;
container.querySelector('#counter-button').addEventListener('click', increment);
return container;
};
return { render };
})();
// 使用组件
document.body.appendChild(CounterComponent.render());
总结
原生 JavaScript 实现组件化的方法包括:

- 使用 ES6 类封装组件逻辑。
- 通过
Custom Elements定义可复用的 HTML 元素。 - 使用事件驱动实现组件通信。
- 通过闭包和模块化避免全局污染。
每种方法适用于不同场景,可以根据需求选择合适的方式。






