Home > Software engineering >  Vue: how to have conditional slot components?
Vue: how to have conditional slot components?

Time:09-28

I have an array of 10 items that have half of them with the type: 'Normal' and the other half with the type: 'Variant'. I am trying to pass them into MyComponent and then slot in Component1 if the type is Normal and slot in Component2 if the type is Variant.

I am having an issue because I keep getting Component1 slotted in all 10 times though instead of half Component1 and half Component2

Parent

 <MyComponent :items="items">
    <template v-slot="slotProps">
      <Component1
        v-if="slotProps.item.type === 'Normal'"
      />
      <Component2
        v-if="slotProps.item.type === 'Variant'"
        :class="$style.gridCover"
      />
    </template>
  </MyComponent>

MyComponent.vue

   <template v-for="(item, index) in items">
        <div
          :key="index"
          :class="$style.gridItem"
        >
          <slot :item="item"></slot>
        </div>
    </template>

CodePudding user response:

I just saw the object in the documentation called slotProps. Is your issue stemming from something like this?

What is slotProps.item supposed to contain? If it's distinct from the array of items then detailing the data might help.

CodePudding user response:

  1. Make two name slot in MyComponent.vue

  2. And Then use v-if inside MyComponent.vue, not in Parent

  • Related