我有 3 个组件,一个显示评论,一个显示评论列表,一个管理应该显示的内容。
当用户单击评论时,Comment 组件会发出一个“comment-selected”事件,并且 CommentsList 组件会监听它以将其转发(也通过执行 $emit)到 CommentsView 组件。
所以基本上我必须将一个事件从一个组件传递给祖父母。
Comment 和 CommentsList 之间的通信正在工作,我可以在 Vue 开发工具中看到 CommentsList 中的第二个 $emit 也在工作,但从未触发 CommentsView 上的侦听器。
但是,如果我在 CommentsList 中执行相同的 $emit,但在其他地方,例如在 mount() 而不是“comment-selected”事件侦听器中,它会起作用。
以下是组件:
<template>
<div>
<ul class="comments-list list-unstyled">
<li class="comments-list-item" v-for="comment in comments" :key="comment.id">
<app-comment :comment="comment" :post-id="postId" @comment-selected="comment => onSelect(comment)" />
</li>
</ul>
</div>
</template>
<script lang="ts">
import AppComment from './Comment.vue';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Comment } from '@/models/comment';
@Component({
name: 'comments-list',
components: {
AppComment,
},
})
export default class CommentsList extends Vue {
@Prop({ type: String, required: true }) private readonly type!: string;
@Prop({ type: Number, required: true }) private readonly postId!: number;
@Prop({ type: Array as () => Comment[], required: true }) private readonly comments!: Comment[];
private onSelect(comment: Comment) {
// This function is called and the event is emitted in the Vue dev tools
this.$emit('comment-selected', comment);
}
}
</script>
<template>
<div class="comments-view-shape">
<app-comments-list :type="type" :post-id="postId" :comments="comments" @comment-selected="comment => onSelect(comment)" />
</div>
</template>
<script lang="ts">
import AppCommentsList from './CommentsList.vue';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Comment } from '@/models/comment';
@Component({
name: 'comments-view',
components: {
AppCommentsList,
},
})
export default class CommentsView extends Vue {
@Prop({ type: String, required: true }) private readonly type!: string;
@Prop({ type: Number, required: true }) private readonly postId!: number;
@Prop({ type: Array as () => Comment[], required: true }) private readonly comments!: Comment[];
private onSelect(comment: Comment) {
// This function is never called but if I do an $emit in CommentsList, outside the v-on callback (like in mounted), it works
console.log(comment);
}
}
</script>
为什么这不起作用?