1
votes

In a specific use-case, I have to access the DOM element inside a slot to get its rendered width and height. With normal slots, this works by accessing this.$slots.default[0].elm.

Now I added a scoped-slot to access data inside the component, which led to this.$slots being empty and breaking my code.

How is it possible to access the DOM element of a slot that is using a slot-scope?

Basic example code (notice while using a scoped-slot, this.$slots results in {}; while using a normal slot, it results in {default: Array(1)}):

App.vue:

<template>
  <div id="app">
    <HelloWorld v-slot="{ someBool }">
      <p>{{ someBool }}</p>
      <h1>Hello</h1>
    </HelloWorld>
    <HelloWorld>
      <h1>Hello</h1>
    </HelloWorld>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  components: {
    HelloWorld,
  },
};
</script>

HelloWorld.vue:

<template>
  <div class="hello">
    <slot :someBool="someBool" />
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      someBool: false,
    };
  },
  mounted() {
    console.log(this.$slots);
  },
};
</script>
1

1 Answers

2
votes

Use $scopedSlots, which includes both scoped slots and non-scoped slots:

export default {
  mounted() {
    console.log(this.$scopedSlots.default())
  }
}

demo