【发布时间】:2020-10-24 05:34:05
【问题描述】:
在特定用例中,我必须访问插槽内的 DOM 元素以获取其呈现的 width 和 height。对于普通插槽,这可以通过访问 this.$slots.default[0].elm 来实现。
现在我添加了一个 scoped-slot 来访问组件内的数据,这导致 this.$slots 为空并破坏了我的代码。
如何访问使用 slot-scope 的 slot 的 DOM 元素?
基本示例代码(注意,使用作用域槽时,this.$slots 生成 {};使用普通槽时,生成 {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>
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component