返回
原生JS优雅封装Table组件,代码精致优雅,让你耳目一新
前端
2023-10-05 08:15:12
前言
在前端开发中,组件是不可或缺的一部分。它可以帮助我们复用代码,提高开发效率,同时保持代码的可维护性。在这篇文章中,我们将使用原生JS来封装一个Table组件。这个组件将具有高度的可定制性,可以满足你项目的不同需求。
代码实现
首先,我们需要创建一个构造函数来初始化Table组件。在这个构造函数中,我们将传入一个对象,其中包含了组件的配置参数。
function Table(options) {
this.el = options.el;
this.data = options.data;
this.columns = options.columns;
this.width = options.width || '100%';
this.init();
}
接下来,我们需要在init方法中初始化组件。在这个方法中,我们将创建表格元素并将其添加到DOM中。
Table.prototype.init = function() {
this.table = document.createElement('table');
this.table.classList.add('table');
this.table.style.width = this.width;
this.thead = document.createElement('thead');
this.tbody = document.createElement('tbody');
this.table.appendChild(this.thead);
this.table.appendChild(this.tbody);
this.el.appendChild(this.table);
this.renderHeader();
this.renderBody();
};
在renderHeader方法中,我们将创建表头并将其添加到表格中。
Table.prototype.renderHeader = function() {
const tr = document.createElement('tr');
this.columns.forEach((column) => {
const th = document.createElement('th');
th.textContent = column.title;
tr.appendChild(th);
});
this.thead.appendChild(tr);
};
在renderBody方法中,我们将创建表体并将其添加到表格中。
Table.prototype.renderBody = function() {
this.data.forEach((row) => {
const tr = document.createElement('tr');
this.columns.forEach((column) => {
const td = document.createElement('td');
td.textContent = row[column.key];
tr.appendChild(td);
});
this.tbody.appendChild(tr);
});
};
最后,我们需要在组件上添加一些方法来允许用户操作表格。例如,我们可以添加一个方法来对表格进行排序。
Table.prototype.sort = function(columnKey) {
this.data.sort((a, b) => {
return a[columnKey] - b[columnKey];
});
this.renderBody();
};
使用组件
现在,我们可以使用Table组件来创建表格了。
const table = new Table({
el: document.getElementById('table'),
data: [
{
name: 'John Doe',
age: 25
},
{
name: 'Jane Doe',
age: 30
}
],
columns: [
{
key: 'name',
title: 'Name'
},
{
key: 'age',
title: 'Age'
}
],
width: '500px'
});
table.sort('age');
总结
在这篇文章中,我们学习了如何使用原生JS来封装一个Table组件。这个组件具有高度的可定制性,可以满足你项目的不同需求。掌握组件封装技巧,可以大大提高你的前端开发效率。