docs icon indicating copy to clipboard operation
docs copied to clipboard

Add Documentation for passing slots to child components

Open LuWa-at-work opened this issue 1 year ago • 2 comments

Hey i found this solution for passing slots to child components of a component. I think this should be in the official docu, because it's a cool trick and has a few usecases 😊

Code to pass on the $slots:

<template v-for="(index, name) in $slots" v-slot:[name]>
  <slot :name="name" />
</template>

Code to pass on the $scopedSlots require some more configuration, but it is similar to passing the $slots:

<template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">
  <slot :name="name" v-bind="data"></slot>
</template>

By defining the templates like this in our parent component we passing on all the slots defined at the place where we use the parent component.

source:

https://devinduct.com/blogpost/59/vue-tricks-passing-slots-to-child-components

LuWa-at-work avatar May 31 '23 08:05 LuWa-at-work

lets work on this i fine out that it will be need and of great us to the user community

martcpp avatar Oct 10 '23 19:10 martcpp

This is a common and useful recipe, but needs to be updated for Vue3 and TS. What I found from research was a pattern like this:

<template>
    <template v-for="slotName of slotNames" #[slotName]>
      <slot :name="slotName" />
    </template>
</template>

<script lang="ts">
  export default defineComponent({
    computed: {
      // This function is here simply to cast the result so TS is happy.
      slotNames() {
        return Object.keys(this.$slots) as 'default'[];
      },
    },
  });
</script>

asselin avatar Nov 14 '23 14:11 asselin