效果:
爷爷组件
<theme-table
:columns="columns"
:data-source="data"
:hasIndex="true"
:hasFixed="true"
:pagination="pagination"
@changePage="handleChange"
@update:selectedList="handleSelect"
indexWidth="100"
>
<template v-slot:villageproperty="{ scope }"> {{ scope.row.village_property }}</template>
</theme-table>
clumns和data数据
export const tableColumns = [
{
label: '乡村',
dataIndex: 'village',
},
{
label: '区县',
dataIndex: 'country',
},
{
label: '地市',
dataIndex: 'city',
},
{
scopedSlots: 'villageproperty', //插槽名称
label: '村庄属性',
dataIndex: 'village_property',
// align: 'right',
},
];
export const data = [
{
id: 66,
city: '湖州市',
country: '长兴县',
village: '八都岕片区',
village_property: 'AAA景区村,市级法治村,省级文明村',
invest_num: 1948,
pic: null,
project_nums: 20,
},
];
父亲组件
<div class="table-info">
<CommonTable v-bind="$attrs">
<!-- 动态插槽-->
<template v-for="(item, index) in slotArr" :key="index" v-slot:[item]="{ scope }">
<slot :scope="scope" :name="item" />
</template>
</CommonTable>
</div>
<script setup>
import { useAttrs, ref } from 'vue';
const attrs = useAttrs();
const slotArr = ref([]);
function computedAttrs(attrs) {
attrs.columns.forEach((item) => {
if (item.scopedSlots) {
slotArr.value.push(item.scopedSlots);
}
});
}
computedAttrs(attrs);
</script>
子组件
<el-table
ref="commonTable"
:data="dataSource"
tooltip-effect="dark"
:height="height"
:max-height="maxHeight"
style="width: 100%"
@selection-change="handleSelectionChange"
@sort-change="(sortProp) => $emit('sort-change', sortProp)"
>
<el-table-column label="序号" type="index" :width="indexWidth" :index="indexMethod" v-if="hasIndex" />
<template v-for="(column, index) in columns">
<--!动态插槽列-->
<el-table-column
v-if="column.scopedSlots"
:key="index"
:label="column.label"
:width="column.width"
:min-width="column.minWidth"
:align="column.align"
>
<template v-slot="scope">
<slot :scope="scope" :name="column.scopedSlots"></slot>
</template>
</el-table-column>
<--!非动态插槽列-->
<el-table-column
v-else
:key="index + 'key'"
:prop="column.dataIndex"
:label="column.label"
:width="column.width"
:min-width="column.minWidth"
:show-overflow-tooltip="column.showOverflowTooltip || false"
:sortable="column.sortable"
:align="column.align"
></el-table-column>
</template>
</el-table>
总结:要实现根据数据设置的动态插槽数量需要在子组件和父亲组件中都动态注册相同数量且对应的具名插槽。