在特定用例中,我必须访问插槽内的 DOM 元素才能获取其渲染的宽度
和高度
。对于普通插槽,可以通过访问 this.$slots.default[0].elm
来实现。
现在我添加了一个作用域插槽来访问组件内的数据,这导致 this.$slots
为空并破坏了我的代码。
如何访问使用槽位范围的槽位的 DOM 元素?
基本示例代码(请注意,使用作用域插槽时,this.$slots
会生成 {}
;使用普通插槽时,会生成 {默认:数组(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>
最佳答案
使用$scopedSlots
,其中包括作用域插槽和非作用域插槽:
export default {
mounted() {
console.log(this.$scopedSlots.default())
}
}
关于javascript - 使用 v-slot (scoped-slot) 时访问 this.$slots,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62716321/