vue.jsvuejs2v-slot

wrap v-slot element in different parent based on condition


I have a template:

<template v-slot:title>
  {{ $t('title') }}
</template>

and a component:

<v-col cols="12">
 <h5 class="text-h5">
   <slot name="title" />
 </h5>
</v-col>

I want to wrap the slot with an <h4> tag only for one particular instance. I tried wrapping it inside the template, but it had no effect. How can I swap the element that wraps the slot?


Solution

  • You could pass the type of tag you want to the component using a non mandatory prop and wrap the content into a dynamic component based on the passed value (in the example h2, h3 and h4 are correct values)

    In the component template :

    <v-col cols="12">
      <component :is="wrapper" :class="`text-${wrapper}`">
        <slot name="title" />
      </component>
    </v-col>
    

    In the component script :

    props: {
      wrapper: {
        type     : String,
        required : false,
        default  : 'h5',
        validator: value => [ 'h2', 'h3', 'h4' ].includes(value)
      }
    }