Home > Software engineering >  Vue 3 How to pass slots through multiple components
Vue 3 How to pass slots through multiple components

Time:02-01

I'm trying to make a huge table reusable throughout my project with specified cells.
I want to pass my different cell components into my table component.
But I can't figure out how to pass a named slot through more than one child.
I'm using Vue v3.2.45

I'm expected to be able to use the slotProps of my named slot cell in App.vue
Like I did with id with the named slot test

I made a playground to make myself clear here

// 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 >Row above is {{ id }}</div>
    </template>
  </Table>
</template>
// Table.vue
<template>
  <div >
    <template v-for="(row, rowI) in table.tree" :key="rowI">
      <Row :row="row" />
      <slot name="test" :id="rowI" />
    </template>
  </div>
</template>
// Row.vue
<template>
  <div >
    <div  v-for="(cell, cellI) in row.data" :key="cellI">
      <slot name="cell" :cell="cell" />
    </div>
  </div>
</template>

CodePudding user response:

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

<!-- Table.vue -->
<template>
  <div >
    <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>
  • Related