search

Home  >  Q&A  >  body text

Vue 3 how to pass slots through multiple components

<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>
P粉216203545P粉216203545462 days ago580

reply all(1)I'll reply

  • P粉644981029

    P粉6449810292023-08-27 18:28:41

    You can expose the cell slot in the Table component and use it in App.vue

    <!-- Table.vue -->
    <template>
      <div class="table">
        <template v-for="(row, rowI) in table.tree" :key="rowI">
          <Row :row="row">
            <template #cell="{ cell }">
              <slot name="cell" :cell="cell"></slot>
            </template>
          </Row>
          <slot name="test" :id="rowI" />
        </template>
      </div>
    </template>
    

    reply
    0
  • Cancelreply