我正在使用渲染函数有条件地渲染子组件。这是父组件与子组件的示例:
<Parent :index="1">
<Child> ... </Child>
<Child> ... </Child>
<Child> ... </Child>
</Parent>
在
Parent
组件的渲染函数中,我有以下代码来有条件地渲染子组件,如下所示:
return () => {
const content = slots.default?.();
const children = content?.filter(child => child.type === Child);
const childToRender = children?.[props.index] ?? h('div')
return h('div', {}, () => [childToRender]);
}
代码按预期工作。
但是,我想用另一个组件包装一个子组件。例如这样:
<Parent :index="1">
<Child> ... </Child>
<ChildWrapper> ... </ChildWrapper>
<Child > ... </Child>
</Parent>
其中
ChildWrapper.vue
看起来像这样:
<template>
<Child> <slot/> </Child>
</template>
显然过滤器函数 (
content?.filter(child => child.type === Child)
) 不会拾取 Child
组件中的 ChildWrapper
组件。
如果我检查 ChildWrapper VNode 的 Children 属性,它会显示一个对象(具有默认槽函数),而不是我期望的带有
Child
组件的数组。所以我的问题是如何获取嵌套的 Child
组件?
假设父组件是
Tab
或 Carousel
组件,子组件是 TabItem
或 CarouselItem
组件。我制作 ChildWrapper
组件的原因是为了扩展/覆盖默认 Child
组件中的一些 props。父组件和子组件都来自组件库,它不知道 ChildWrapper
是什么,因此父组件无法控制 ChildWrapper
应该如何渲染。
2 种方法。
exports defineState({
visibleChildType: 'type'
})
在父组件中,使用所需的任何逻辑设置状态值。
然后,将条件渲染条件从父级移到子级本身,同时导入状态:就像,
// ChildComponent.vue
<template>
<div v-if="type === visibleChildType" />
</template>
<script>
import visibleChildType from 'parentState'
</script>
// ChildComponent.vue
<template>
<ChildWrapper v-if="needsWrapper">
<div />
</ChildWrapper>
<div v-else=" />
</template>
这样,子组件可以在必要时包装自己,并且您的父组件不需要重构。