Vue表格组件开发:如何通过Scoped Slots传递行数据至column-component?
表格组件:将data数据传递给Column组件的作用域插槽
我正在开发一个表格组件,以下是简化场景(实际代码更复杂庞大)。我希望把表格通过data prop传入的数据,传递给column-component的作用域插槽,认为可以通过Celll.vue渲染函数组件实现,但不确定这个思路是否正确。
预期实现效果
<table-component :data="dataTable"> <column-component v-slot="slotProps"> <span>Name:</span> <span>{{ slotProps.row.name }}</span> </column-component> <column-component v-slot="slotProps"> <span>Age:</span> <span>{{ slotProps.row.age }}</span> </column-component> <column-component v-slot="slotProps"> <span>City:</span> <span>{{ slotProps.row.city }}</span> </column-component> </table-component> <script> export default { data() { return { dataTable: [ { name: "Alex", age: "20", city: "Msk" }, { name: "Bob", age: "22", city: "Paris" }, { name: "Dilan", age: "21", city: "London" }, ], }; }, }; </script>
现有组件代码
TableComponent.vue
<template> <table> <tr v-for="(row, rowIndex) in data" :key="rowIndex"> <Celll v-for="(col, colIndex) in columns" :key="colIndex" :vnodes="col" :row="data" /> </tr> </table> </template> <script> import Celll from "./Celll.vue"; export default { components: { Celll, }, props: { data: Array, }, data() { return { columns: [], }; }, mounted() { this.columns = this.$slots.default(); }, }; </script>
ColumnComponent.vue
<template> <slot /> </template> <script> export default {}; </script>
Celll.vue
<script> import { h } from 'vue'; export default { props: { vnodes: { type: Object, required: true, }, row: { type: [String, Number, Object, Array], required: true, }, }, render() { return h('td', null, this.vnodes); }, }; </script>
解决方案:修正代码实现作用域插槽传值
你的思路是可行的,通过Celll组件作为中间层传递行数据给作用域插槽是合理的,只需对现有代码做两处关键修改:
修正TableComponent中row的传递
将Celll组件的:row="data"改为:row="row",确保每个单元格拿到的是当前循环的行对象,而非整个数据数组:<Celll v-for="(col, colIndex) in columns" :key="colIndex" :vnodes="col" :row="row" <!-- 传递当前行数据 --> />修改Celll组件,调用作用域插槽并传值
在Celll的渲染函数中,通过renderSlot方法调用column-component的作用域插槽,并将行数据作为插槽props传入:<script> import { h, renderSlot } from 'vue'; export default { props: { vnodes: { type: Object, required: true, }, row: { type: Object, required: true, }, }, render() { // 调用作用域插槽,传递row数据 const slotContent = renderSlot(this.vnodes.props, 'default', { row: this.row }); return h('td', null, slotContent); }, }; </script>
完成上述修改后,父组件中就能通过slotProps.row访问到当前行的数据,实现预期效果。
内容的提问来源于stack exchange,提问作者magistr4815
相关产品推荐
相关产品推荐

