Vue 3 how to pass slots through multiple components
P粉216203545
2023-08-27 00:15:30
<p>I'm trying to create a huge table with specified cells that can be reused throughout the project. </p><p>
I want to pass different cell components into my table component. </p><p>
But I don't know how to <strong>pass a named slot through multiple child nodes</strong>. </p><p>
I'm using <strong>Vue v3.2.45</strong></p>
<p>I want to be able to use my named slot <code>cell</code>'s slotProps</p><p> in App.vue
Like I did with <code>id</code> and the named slot <code>test</code></p>
<p>I created a playground here to make myself clear</p>
<pre class="brush:js;toolbar:false;">// App.vue
<script setup lang="ts">
import { ref } from 'vue'
import { ITable } from './types.ts'
import Table from './Table.vue'
const table = ref<ITable>({
tree: [
{ data: [{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }] },
{ data: [{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }] },
],
})
</script>
<template>
<Table :table="table">
<template #cell="{ cell }">
Hello {{ cell.value }}
</template>
<template #test="{ id }">
<div class="row">Row above is {{ id }}</div>
</template>
</Table>
</template>
</pre>
<pre class="brush:js;toolbar:false;">// Table.vue
<template>
<div class="table">
<template v-for="(row, rowI) in table.tree" :key="rowI">
<Row :row="row" />
<slot name="test" :id="rowI" />
</template>
</div>
</template>
</pre>
<pre class="brush:js;toolbar:false;">// Row.vue
<template>
<div class="row">
<div class="cell" v-for="(cell, cellI) in row.data" :key="cellI">
<slot name="cell" :cell="cell" />
</div>
</div>
</template>
</pre></p>
You can expose the
cell
slot in theTable
component and use it inApp.vue