简体   繁体   中英

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()
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM