各大前端组件库中都存在table组件,均支持slot插槽和render渲染,现在就试着探究其中原理:
基本列表
首先制定表格API。表格分为表头thead和数据tbody,所以props也定义为两部分:
- columns: 列配置Array,每一列均为Object:
- title: 列文字
- key: 对应列内容字段名称
- render: 渲染函数
- slot:插槽名称 - data: 数据内容Array
在components目录中新建table目录,创建table.vue文件:
// components/table
<template>
<table>
<thead>
<tr>
<th v-for="(col, index) in columns" :key="index">
{
{
col.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="(col, idx) in columns" :key="idx">
{
{
row[col.key] }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
columns: {
type: Array,
default: () => []
},
data: {
type: Array,
default: () => []
},
}
};
</script>
<style>
table {
width: 100%;
border