如何在 Vue 中将重复出现的组件事件传递给父级

How to get recurring component event to parent in Vue

所以我有一个 Commentbox 组件,它使用递归在嵌套的父子层次结构中列出用户评论 (Comment)。

// Commentbox.vue (child)
<template>
   <comment :comments="comments"></comment-box>
</template>

我们假设传递给这个子组件的数据是

[
  { id: a, parent: c, children: [], comment: cdoisdskds ....}
  { id: b, parent: a, children: [...,...], comment: bjdskdls .... }
]

然后在子组件中,我们有如下代码结构:

<template>
   <div v-for="(comment, index) in comments" :key="index" >

      <div  v-if="comment.children" @click="this.$emit('repling', somedata )" > is parent layout </div>
      <div v-else >

        //is child - do the parent-child check layout etc...
        <comment :comment.children></comment>

      </div>
   </div>
<template>

布局很好,没有问题,但当我尝试从子项向父项发出事件时出现问题。

它在父组件中工作,我可以成功地为直接子组件获取事件...

<comment-box>
  <comment @replying="dostuff"></comment>
</comment-box>

问题出在我单击子组件时,因为它是一个重复出现的组件,人们会期望它的行为方式相同,但事实并非如此。该事件没有引起父组件的共鸣。

如何在 vue 中处理这种边缘情况?

您应该将 $listeners 从父级传递给子级,或者重新发射甚至从子级返回给父级。最简单的方法是在开始递归组件时添加 v-on="$listeners"

<template>
   <div v-for="(comment, index) in comments" :key="index" >

      <div  v-if="comment.children" @click="$emit('replying', somedata)" > is parent layout </div>
      <div v-else >
        <comment v-on="$listeners" :comment.children></comment>
      </div>
   </div>
<template>

参见 v-on="$listeners" 添加。