如何在 Vuejs 中从子项$emit到父级以重置数据列表



我有一个包含以下代码的父组件:

mounted() {             
var self = this;
this.getCandidates();
this.$on('updateListCandidates', () => {
self.getCandidates();
});
},

多亏了这一点,我可以通过拨打$emit ('updateListCandidates')来更新我的列表

我有一个像这样导入的子组件:

<DeleteCandidate :item="scope.row"></DeleteCandidate>

在这个子组件中,我有一个 Destroy 函数。我要求它刷新我的列表,这要归功于$emit元素正确删除。

async destroyItem() {
await this.deleteItem.delete(`candidates/${this.deletingItem.id}`)
.then(() => {
this.$emit('updateListCandidates');
this.$message({
message: `Candidate (${this.deletingItem.full_name}) correctly deleted.`,
type: 'success'
});
});
},

但它不起作用。

为什么?以及如何解决我的问题?

如果我在我的父组件中这样做,它可以工作。我认为这是因为我在子组件中,但在这种情况下我根本不知道如何对父组件进行$emit

我指定我的候选人被很好地删除。我在控制台中没有任何错误消息。

谢谢

首先,为什么不删除此代码

this.$on('updateListCandidates', () => {
self.getCandidates();
});

并直接拨打getCandidates而不是做$emit ('updateListCandidates')

其次,(您的实际问题的答案)您必须收听直接父级中的事件,并在您从孩子发出时在那里执行操作。否则,仅从子级发出(而不是在父级中侦听)不会影响任何事情。所以你可以在父母做

<DeleteCandidate :item="scope.row" @updateListCandidates="getCandidates"></DeleteCandidate>

我假设getCandidates是在父级中定义的。

最新更新