【发布时间】:2021-09-12 21:18:57
【问题描述】:
我有一个具有默认插槽的组件,并且在渲染函数中,我试图将 slot 中的每个项目包装在一个 div 内,以便更好地控制布局。
我需要抓取其中一个插槽元素类(如果存在)以将其添加到包装器元素中,但 VNode 元素在函数运行时没有 elm 或 $el 可用,它是还是undefined。
父组件模板:
<Parent>
<span>child 1</span>
<p class="push">child 2</p>
<Child>child 3</Child>
</Parent>
预期的渲染结果:
<Parent>
<Wrapper>
<span>child 1</span>
</Wrapper>
<Wrapper class="push">
<p>child 2</p>
</Wrapper>
<Wrapper>
<Child>child 3</Child>
</Wrapper>
</Parent>
目前,这是我的渲染函数,它正确地包装了每个元素,但是它没有在 slot children 中找到类,它似乎无法访问!
render(createElement) {
const childs = [];
this.$slots.default.forEach(item => {
if (item.tag) {
console.log(item.elm, item.componentInstance); // both returns undefined
childs.push(createElement("Wrapper", [item]));
}
});
return createElement(this.tag, { class: this.classes }, childs);
}
那么,如何在渲染函数中访问 slot 元素的类?
【问题讨论】:
标签: javascript vue.js jsx