【问题标题】:Vue $emit in Promise承诺中的 Vue $emit
【发布时间】:2020-04-25 13:09:21
【问题描述】:

我正在处理基于 Promise 的图像上传。在“then” - 回调中,我想 $emit 一个事件。我称之为“成功”。我的 VueDevTools 向我显示了一个成功事件,但在父组件中,从未调用过“链接”方法。有没有可能 this.$emit('success') 在 Promises 中不起作用?

示例代码 - 子组件:

UsersAPI.updateAvatar(this.user.id, data, fileExt).then(res => {
  if (res) {
    Helpers.callToast(this, 'is-success', this.$root.$t('profile.avatar_upload'))
    this.$emit('success')
  }
})

示例代码 - 父组件

<Avatar @success="test" :user="user" />

从不调用父组件中的方法“test”,但在 vue 开发工具中调用事件。如果我在 Promise 之前发出事件,我会得到我想要的结果。

你能帮帮我吗? 亲切的问候

【问题讨论】:

  • 在 Promise 中使用 $emit 应该可以正常工作,只要你得到正确的 this 绑定。它在提供的代码中似乎是正确的,如果它是错误的,您会看到一个关于 $emit 不是函数的控制台错误。你如何确定test 没有被调用?我建议在子组件中添加一些控制台日志记录或debugger 语句,以准确检查其中发生了什么。我目前的感觉是问题不在于您发布的代码。
  • 顺便说一句,this.$root.$t 是什么?我认为有一个拼写错误,应该是this.$root.$emit 不是吗?
  • 另外,你能告诉我们Helpers.callToast这里有什么吗?

标签: javascript vue.js promise


【解决方案1】:

在我的例子中,子组件是在初始化 API 请求时使用“v-if”指令从父组件中移除的

然后,当我的请求完成时,子组件正确地发出了一个事件,但是此时子组件没有呈现在父组件的 DOM 中,因此父组件无法监听该事件。

【讨论】:

  • 这正是我的问题。感谢您的评论。
【解决方案2】:

我认为这是因为 'this' 绑定。

需要将Vue组件实例的this绑定到回调函数中。

const callbackFn = function(res) {
  if (res) {
    Helpers.callToast(this, 'is-success', this.$root.$t('profile.avatar_upload'))
    this.$emit('success')
  }
}.bind(this);

UsersAPI.updateAvatar(this.user.id, data, fileExt).then(callbackFn)

或者你可以简单地创建一个新变量来保存你的 Vue 实例,然后引用你的回调函数来使用它。

const self = this;
UsersAPI.updateAvatar(this.user.id, data, fileExt).then(res => {
  if (res) {
    Helpers.callToast(this, 'is-success', self.$root.$t('profile.avatar_upload'))
    self.$emit('success')
  }
})

【讨论】:

  • 我已经尝试过了,但它不起作用。我再给你看一些代码:pastebin.com/jEEtsJwh
  • 你能把这行Helpers.callToast(this, 'is-success', this.$root.$t('profile.avatar_upload'))注释掉,然后再试一次吗?我想知道它是否有问题
  • 我确实注释掉了 Helpers.callToast 行,但没有任何改变......它没有影响
猜你喜欢
  • 2019-05-11
  • 2016-08-25
  • 2018-06-23
  • 2021-09-20
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多