简体   繁体   English

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

[英]How to $emit from child to parent in Vuejs for reset data list

I have a parent component that contains this code: 我有一个包含以下代码的父组件:

mounted() {             
  var self = this;

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

Thanks to this I can update my list by calling $emit ('updateListCandidates') 因此,我可以通过调用$emit ('updateListCandidates')更新列表

I have a child component that I import like this: 我有一个这样导入的子组件:

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

In this child component, I have a Destroy function. 在此子组件中,我具有销毁功能。 I ask it to refresh my list thanks to $emit once the element correctly deleted. 正确删除元素后,我希望它通过$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'
            });
          });
      },

BUT it doesn't work. 但是它不起作用。

Why ? 为什么呢 And how to solve my problem? 以及如何解决我的问题?

If I do that in my parent component, it works. 如果我在父组件中执行此操作,那么它将起作用。 I think it's because I'm in a child component but I do not know at all how to do a $emit on a parent in this case 我认为这是因为我在子组件中,但是在这种情况下我根本不知道如何在父组件上进行$emit

I specify that my candidate is deleted well. 我指定我的候选人已被删除。 I do not have any error messages in the console. 我在控制台中没有任何错误消息。

Thank you 谢谢

Firstly, why don't you remove this code 首先,为什么不删除此代码

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

and directly call getCandidates instead of doing $emit ('updateListCandidates') ? 直接调用getCandidates而不是执行$emit ('updateListCandidates')吗?

Secondly, (the answer to your actual question) you must listen to event in direct parent and perform action there whenever you emit from child. 其次,(对您实际问题的回答)您必须听直接父母的事件,并在您从孩子那里冒出来时在那里采取行动。 Otherwise just emitting from child (and not listening in parent) will not effect anything. 否则,仅仅从孩子身上散发出来(而不是在父母身边听)不会有任何影响。 So you can do in parent 所以你可以在父母那里做

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

I assume getCandidates is defined in parent. 我假设getCandidates是在父getCandidates中定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM