Home > database >  How to get slots or slotted elements as refs?
How to get slots or slotted elements as refs?

Time:10-18

I need to interact with a slotted element as soon as it is slotted. I tried the following:

<script setup lang="ts">
import { onMounted, ref } from 'vue';

const $slot = ref<HTMLSlotElement | null>(null);

onMounted(() => {
  console.log($slot.value);
  console.log($slot.value?.assignedElements()[0]);
}));
</script>

<template>
  <div>
    <slot ref="$slot"></slot>
  </div>
</template>

However, when I render this component with slotted children I just get undefined in the console. What am I doing wrong?

CodePudding user response:

Give your slot a name instead of a ref and access slots using the useSlot() helper.

<script setup lang="ts">
import { useSlots, onMounted } from 'vue';

const slots = useSlots();

onMounted(() => {
  if (slots && slots.$slot) {
    console.log('slots.$slot()', slots.$slot());
  }
});

</script>

<template>
  <div>
    <slot name="$slot"></slot>
  </div>
</template>

Once slot content is given by a parent component you'll find that slots.$slot() contains an array of the virtual DOM nodes that make up the slot's content

  • Related