首页 > 解决方案 > Vue 中可能有重复的插槽吗?

问题描述

我已经设置了复制存储库:

https://github.com/devidwong/recurring-slot

我只使用 Vue 运行时,所以我不能附加小提琴Vue.extend(需要模板编译器)

Vue 3 是相当新的东西。我将其用于探索目的。我不知道这是否适用于 Vue 2,但我只是想知道这个组件是否应该工作:

评论.模板.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. 在我看来,第二个插槽与第一个插槽获得相同的评论道具。我希望有嵌套的评论并只定义一次内部的东西。

这可能吗?

标签: javascriptvue.jsvuejs2vue-componentvuejs3

解决方案


不要通过 slot 再次将评论暴露给父组件,只需在CommentComponent 中打印作者姓名和评论:

<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 评论风格。


推荐阅读