Vue3中Slot插槽透传,二次封装Arco的table组件
Vue3 插槽透传
需求是这样, 对acro的table表格进行二次封装。
封装成一个组件。要求二次封装的组件可以将slot透传给原生的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',
- },
- ];
复制代码 步骤
首先我们先明白原组件的使用。中的table组件, 当定义了插槽就渲染插槽。当没有定义的时候就正常显示table表格中的数据。
因为我们要对table组件进行二次封装,所以我们要将table中的插槽透传出去。下面是实现原理。
1. 知道父组件传递了一个slot
这里我们要用一个vue3中的API,, 我们要用这个api来判断父组件是否传递了插槽。
- 从slots中获取父组件传的插槽信息,如果没有则就使用中默认的。即正常展示。当自定义了插槽, 就选择插槽的内容。
- 插槽的参数传递是
- v-slot:[key]="{ record, rowIndex, column }"
复制代码 这里的参数是中传递的。
- 然后我们在透传给我们的自己的插槽。
- :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>
复制代码 总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:https://www.jb51.net/javascript/3399097fh.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |