Reputation: 378
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>
Upvotes: 2
Views: 7744
Reputation: 534
Maybe not directly related but wanted to share how to access slot values.
<template>
<span class="ml-5">
The Slot Values: <span class="text-yellow-400">{{filterValues}}</span>
</span>
</template>
<script>
export default {
data() {
return {
filterValues: ''
}
},
mounted() {
this.filterValues = this.$slots.default()[0].children
}
}
</script>
...
<product-filter-vue>Instrument, FX</product-filter-vue>
...
Upvotes: 0
Reputation: 138276
Use $scopedSlots
, which includes both scoped slots and non-scoped slots:
export default {
mounted() {
console.log(this.$scopedSlots.default())
}
}
Upvotes: 2