我已经设置了复制存储库:
https://github.com/devidwong/recurring-slot
我只使用Vue运行时,所以我不能使用Vue.extend
(需要模板编译器(
Vue 3是相当新的东西。我把它用于探索目的。我不知道这是否能在Vue 2上工作,但我只是想知道这个组件是否能正常工作:
comment.template.html:
<div class="comment">
<slot :currentComment="comment"></slot>
<Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply">
<slot :currentComment="reply"></slot>
</Comment>
</div>
用法:
comments.template.html
<Comment v-for="comment in comments" :key="comment.id" :comment="comment">
<template #default="{ currentComment }">
<div>by {{ currentComment.author }}</div>
</template>
</Comment>
结构:
comments: [
{
id: 1,
author: 'Goodman',
replies: [
{
id: 11,
author: 'RepeatingMan',
replies: [
{
id: 111,
author: 'ExpectedMan',
replies: [
{
id: 1111,
author: 'MelodyOfFuture',
replies: []
}
]
}
]
}
]
}
]
我得到了Repeatimg man
渲染3次而不是ExpectedMan
和MelodyOfFuture
。在我看来,第二个槽得到了和第一个槽相同的评论道具。我希望有嵌套的评论,并且只定义一次内部内容。
这可能吗?
不要通过slot再次向父组件公开注释,只需在Comment
组件中打印作者姓名及其注释:
<div class="comment">
{{comment.author}}
<Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply">
<slot :currentComment="reply"></slot>
</Comment>
</div>
父组件:
<Comment v-for="comment in comments" :key="comment.id" :comment="comment">
</Comment>
现场演示
在现场演示中,我试图模拟stackoverflow的评论风格。
回购更新
https://github.com/devidwong/recurring-slot
父级:
<Comment
v-for="comment in comments"
:key="comment.id"
:comment="comment"
:detailsComponent="CommentDetails"
>
<template #default="{ currentComment }">
<CommentDetails
:currentComment="currentComment"
/>
</template>
</Comment>
子级:
<div class="comment">
<slot :currentComment="comment"></slot>
<Comment
v-for="reply in comment.replies"
:key="reply.id"
:comment="reply"
:detailsComponent="detailsComponent"
>
<template #default="{ currentComment }">
<component
:is="detailsComponent"
:currentComment="currentComment"
:detailsComponent="detailsComponent"
/>
</template>
</Comment>
</div>
详细信息:
<div>
by {{ currentComment.author }}
</div>
不要忘记将CommentDetails(在父级中(声明为组件和数据条目:
{
components: {
Comment,
CommentDetails
},
data: () => ({
CommentDetails,
comments: [...]
})
}