4

how do I reliably access the root HTML element in a slot? I tried slots.default()[0].el but its not consistent. I realized if the slot is a simple html, it is not null, which is great, but if it has some vue directives or components, it will be null. So how can I reliably get hold of the root HTML Element in a slot?

icube
  • 2,578
  • 1
  • 30
  • 63

2 Answers2

0

I found one possible solution: that is to have the slot content provider to explicitly set the element you want to reference to by providing a slot-prop method to invoke. And also since Vue 3 template supports multiple root elements, its not really reliable to assume that the slot will always have one root element.

Here is the example of the solution:

<template>
  <slot :set-element="(el) => element = el"></slot>
</template>
<script setup lang="ts">
  import { ref, watchEffect } from "vue";
  const element = ref<Element | null>(null);

  watchEffect(() => {
    console.log(element.value);
  });
</script>

In the usage of the component, inject the slot props and use the Function Refs syntax

<MyComponent v-slot="{ setElement }">
  <div :ref="(el) => setElement(el)">...</div>
  <div>...</div>
</MyComponent>
icube
  • 2,578
  • 1
  • 30
  • 63
0

You could access a slot's root HTML element directly with the slot's vnode property and in your component script, you can using this.$refs.root.

Here is an example:

<template v-slot:[slotName]="{ vnode }">
  <div ref="root">
    <!-- your slot content goes here -->
  </div>
</template>

mounted() {
      const root = this.$refs.root as HTMLElement;
      console.log(root);
    }

EDIT

The official documentation for v-slot can be found here: https://vuejs.org/api/built-in-directives.html#v-slot

Instead, the official documentation for $refs can be found here: https://v3.vuejs.org/guide/composition-api-template-refs.html

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 09 '23 at 07:17