vue3中slot插槽透传,二次封装arco的table组件
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>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论