2017-05-25 106 views
0

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

不工作(从内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内部发出数据,则不会调用此方法。

+0

你确定'response.data.res'是'true'吗? – thanksd

+0

是的,我检查了console.log消息。 response.data.res是真实的。我用console.log语句修改了我的代码,你能否检查一下。 @thanksd –

+2

我无法重现您的问题。看到这个小提琴:https://jsfiddle.net/nxcne6zr/ – thanksd

回答

0

使用Vue.nextTick等待更新。

试试这个里面爱可信:

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

感谢您的回答,请参阅下面的解决方案。 @Matija –

0

谢谢您的回答。

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

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

这就是为什么$ emit('updateparentdata')函数在axios调用内没有按预期执行。

解决方案1:

我移动$发射(“关闭”)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'); 
      } 
     }); 
    } 
}, 

解决方案2:

正如@Matija祖潘契奇提到,我Vue.nextTick试图等待更新。这种方法也起作用。