Vue3中如何通过插槽向子组件传递模板?
解决父组件向子组件传递自定义模板的问题
你的核心问题是:父组件中定义的列自定义插槽(如item-is_admin、item-id)没有被正确传递给子组件内部的EasyDataTable。当前子组件仅用<slot />传递了默认插槽内容,而EasyDataTable需要直接接收这些具名插槽才能渲染自定义列模板。
修改子组件代码
将子组件中的<slot />替换为插槽透传写法,把父组件传入的所有具名插槽直接传递给内部的EasyDataTable:
<EasyDataTable class="table-dark table-striped" buttons-pagination :headers="headers" :items="items" v-model:server-options="serverOptions" :server-items-length="serverItemsLength" :loading="loading" rows-per-page-message="Filas por pestaña" > <!-- 透传所有具名插槽 --> <template v-for="(_, slotName) in $slots" v-slot:[slotName]="slotProps"> <slot :name="slotName" v-bind="slotProps" /> </template> </EasyDataTable>
优化父组件代码
父组件无需嵌套v-slot:default,直接定义具名插槽即可,简化写法:
<EasyTable :headers="headers" :url="url"> <template v-slot:item-is_admin="{ is_admin }"> <Icon icon="mdi:check" v-if="is_admin" color="green" width="30" /> <Icon icon="mdi:close" v-if="!is_admin" color="red" width="30" /> </template> <template v-slot:item-id="{ id }"> <button class="btn btn-error btn-xs text-white" @click="axios.delete(`${url}/${id}/`).then(() => router.go(0))" > Eliminar </button> </template> </EasyTable>
原理说明
$slots是Vue组件的内置属性,包含父组件传入的所有插槽内容(键为插槽名称,值为插槽内容)。- 通过
v-for遍历$slots,动态绑定插槽名称和插槽props,就能把父组件的所有具名插槽完整透传给内部的EasyDataTable,让它正确识别并渲染自定义列模板。
内容的提问来源于stack exchange,提问作者Willders Carvajal
相关产品推荐
相关产品推荐

