【问题标题】:$emit is not emitting the message to parent from inside axios$emit 没有从 axios 内部向父级发送消息
【发布时间】:2017-10-26 15:14:18
【问题描述】:

我在子组件中有一个方法,它负责从服务器获取数据,在接收到数据后,我试图将数据发送给父组件。下面的方法来自 Vue.component (child)。问题是,父组件无法接收发出的数据。只是为了检查,我将 $emit 代码移到了 axios 请求调用之外,然后它就可以工作了。如果我从 axios 内部 $emit,它就不起作用。

不工作(从 axios 内部发出):

methods:{
    methodName: function(){
        let self = this;
        axios.get('url')
        .then(function(response){
            if (response.data.res) {
                console.log('response is true, i can see this message');
                self.$emit('updateparentdata',response.data);
            }
        });
        self.$emit('close');
    }
},

工作(从外部 axios 发出):

methods:{
    methodName: function(){
        let self = this;
        self.$emit('updateparentdata','some dummy data');
        axios.get('url')
        .then(function(response){
            if (response.data.res) {

            }
        });
        self.$emit('close');
    }
},

这是我的 html 页面中的组件代码,如果从 updateparentdata 发出某些内容,那么它将调用父 vue 中的“updateData”函数。

<modal 
    v-if="showModal"
    @close="showModal = false"
    v-on:updateparentdata="updateData">
</modal>

这是我在父级vue中的方法,

updateData: function(response){
    console.log(response);
},

在我从子组件发出数据后,不会触发此方法。如果我在 axios 外部发出数据,则调用此方法,但如果我从 axios 内部发出数据,则不调用此方法。

【问题讨论】:

  • 你确定response.data.res 是true?
  • 是的,我用 console.log 消息检查了它。 response.data.res 是真的。我用 console.log 语句修改了我的代码,你能检查一下吗? @thanksd
  • 我无法重现您的问题。看到这个小提琴:jsfiddle.net/nxcne6zr
  • 我找出了问题所在,并在下面提供了修复。感谢您的贡献。 @thanksd

标签: javascript vuejs2 vue-component axios


【解决方案1】:

感谢您的回答。

我发现了问题所在,我在 axios 调用之外调用了 $emit('close') 函数。

由于 axios 调用是异步的,在发出请求后,axios 实例外部的 $emit('close') 实际上会关闭我的模态窗口,该窗口会删除我的整个组件实例。

这就是为什么 axios 调用中的这个 $emit('updateparentdata') 函数没有按预期执行的原因。

解决方案 1:

我在 axios 请求中移动了 $emit('close'),所以在收到响应后我正在关闭模式窗口。

methods:{
    methodName: function(){
        let self = this;
        axios.get('url')
        .then(function(response){
            if (response.data.res) {
                console.log('response is true, i can see this message');
                self.$emit('updateparentdata',response.data);
                self.$emit('close');
            }
        });
    }
},

解决方案 2:

正如@Matija Župančić 所述,我尝试使用 Vue.nextTick 来等待更新。这种方法也有效。

【讨论】:

    【解决方案2】:

    使用 Vue.nextTick 等待更新。

    在 axios 中试试这个:

    this.$nextTick(() => {
      self.$emit('close');
    });
    

    【讨论】:

    • 感谢您的回答,请看下面我的解决方案。 @Matija
    【解决方案3】:

    正如@RubanrajRavichandran 在他的解决方案 1 中提到的那样,self = this 是因为在 axios 中。然后这会发生变化。您可以改用 .then((response) =&gt; {} 和 this 之类的箭头功能,因此您不必使用 self

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-04
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2014-10-08
      相关资源
      最近更新 更多