javascriptvue.jscomponentsslot

How to get number of slot in a VueJS component


I need my component to get slots number are occupied by the parent component
For example:

This is the component:

<template>
  <div>
    <slot/>
  </div>
</template>
<script>
  name: 'comp',
  data() {
    return {
      nslot: 0
    }
  }
</script>

This is the parent

<template>
  <div>
    <component>
      <button slot=""></button>
      <button slot=""></button>
      <button slot=""></button>
      <button slot=""></button>
      ...
    <component/>
  </div>
</template>
<script>
  name: 'comp'
</script>

How i can do? I want to get number of used slot in the "nslot" variable

I prefer using method, (in the component) like:

mounthed() {
  this.nslot = this.getslotnumber()
}

Solution

  • You should use a scoped slot like :

    <template>
      <div>
        <slot :nslot="nslot" />
      </div>
    </template>
    <script>
      name: 'comp',
      data() {
        return {
          nslot: 0
        }
      }
    </script>
    

    in parent :

    <template>
      <div>
        <compt v-slot="{nslot}">
          <button :slot="nslot">{{nslot}}</button>
        <comp/>
      </div>
    </template>
    <script>
      name: 'comp'
    </script>