Home > Net >  How can I accept only one component as slot in vue
How can I accept only one component as slot in vue

Time:01-25

I have a button-group component and I want this component only accepts Button component that I created as slots.

So this is my ButtonGroup component:

<template>
  <div >
    <slot />
  </div>
</template>

<script lang="ts">

export default {
  name: 'ButtonGroup',

  components: {
    Button,
  },
};
</script>

How can I accept only Button component as slot?

CodePudding user response:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div >
    <slot name="button">
     <Button />
    </slot>

  </div>
</template>

<script lang="ts">

export default {
  name: 'ButtonGroup',

  components: {
    Button,
  },
};
</script>

//Use of ButtonGroup component`enter code here`

<ButtonGroup>
 <template #button />
</ButtonGroup>

CodePudding user response:

use render function

<script>
import {h} from 'vue';

export default {
  name: 'ButtonGroup',
  render() {
    const buttons = []
    for (let defaultElement of this.$slots.default()) {
      // case: <button />
      if (defaultElement.type === 'button') {
        buttons.push(defaultElement)
      }
      
      // other component
      // if (defaultElement.type.name === 'Button') {
      //   buttons.push(defaultElement)
      // }
    }
    return h('div', {class: 'button-group'}, buttons)
  }
};
</script>

I referenced here https://vuejs.org/api/render-function.html

  • Related