Vue3 插槽透传
需求是这样, 对acro的table表格进行二次封装。封装成一个 <SearchTable>
组件。要求二次封装的组件可以将slot透传给原生的table组件。如下这样,将SearchTable
中的插槽透传给 <a-table>
<SearchTable
:search-model="searchModel"
:table-cols="cols"
:table-data="tableData"
:pagination="pagination"
@search="searchTableAction"
>
<template #channelCode="{ record, rowIndex, column }">
{{ record }} - {{ rowIndex }} - {{ column }}
</template>
<template #channelName="{ record, rowIndex, column }">
{{ record }} - {{ rowIndex }}- {{ column }}
</template>
<template #status="{ record, rowIndex, column }">
{{ record }} - {{ rowIndex }}- {{ column }}
</template>
</SearchTable>
一共有下面几个字段
const cols = [
{
title: '渠道编码',
dataIndex: 'channelCode',
slotName: 'channelCode',
},
{
title: '渠道名称',
dataIndex: 'channelName',
slotName: 'channelName',
},
{
title: '状态',
dataIndex: 'status',
slotName: 'status',
},
];
步骤
首先我们先明白原组件的使用。
arco
中的table组件, 当定义了插槽就渲染插槽。当没有定义的时候就正常显示table表格中的数据。
因为我们要对table组件进行二次封装,所以我们要将table中的插槽透传出去。下面是实现原理。
1. 知道父组件传递了一个slot
这里我们要用一个vue3中的API,useSlots()
, 我们要用这个api来判断父组件是否传递了插槽。
- 从slots中获取父组件传的插槽信息,如果没有则就使用
arco
中默认的。即正常展示。当自定义了插槽, 就选择插槽的内容。 - 插槽的参数传递是
v-slot:[key]="{ record, rowIndex, column }"
这里的参数是arco
中传递的。 - 然后我们在透传给我们的自己的插槽。
:name="key" v-bind="{ rowIndex: rowIndex, record: record, column: column }"
<template>
<a-table
row-key="id"
:loading="loading"
:pagination="pagination"
:columns="(cloneColumns as TableColumnData[])"
:data="tableData"
:bordered="false"
:size="size"
@page-change="onPageChange"
>
<!-- key 就是 slotName-->
<template
v-for="(item, key, i) in slots"
:key="i"
v-slot:[key]="{ record, rowIndex, column }"
>
<slot
:name="key"
v-bind="{ rowIndex: rowIndex, record: record, column: column }"
></slot>
</template>
</a-table>
</template>
<script lang="ts" setup>
import {
useSlots,
} from 'vue';
const slots = useSlots();
</script>
2. 父组件使用
<SearchTable
:search-model="searchModel"
:table-cols="cols"
:table-data="tableData"
:pagination="pagination"
@search="searchTableAction"
>
<template #channelCode="{ record, rowIndex, column }">
{{ record }} - {{ rowIndex }} - {{ column }}
</template>
<template #channelName="{ record, rowIndex, column }">
{{ record }} - {{ rowIndex }}- {{ column }}
</template>
<template #status="{ record, rowIndex, column }">
{{ record }} - {{ rowIndex }}- {{ column }}
</template>
</SearchTable>