2017-09-05 589 views
2

父母的功能我的问题是,就像这样:Vuejs $emit doesn't fire on callback。 但我在我的项目中使用了superagent。这里是我的代码:

//Parent.vue 
<Child v-on:savevideo="toSaveVideo"/> 
... 
methods:{ 
    toSaveVideo:function(data){ 
    console.log('add'); 
    } 
} 

//Child.vue 
<button @click="toAdd">Add</button> 
... 
methods:{ 
    toAdd:function(){ 
    ... 
    let self = this; 
    superagent 
     .get(url) 
     .query({data:data}) 
     .end(function(err,res){ 
     //trigger parent function 
     let resData = res.body.data; 
     self.$emit('savevideo',resData); 
    }) 
    } 
} 

请求是成功的,但是当父母触发“savevideo”,方法“toSaveVideo”没有打印出任何东西。然而,当我把这些放在回调之外时,一切都很好。 为什么$ emit事件不会在回调中触发?

回答

0

好吧,我想通了。

'V-如果' 绑定的子组件上。

因为在我的项目中,在子组件中,还有另一个触发器'close'来关闭这个子组件,并且它是在回调之外发出的,并且这导致了问题。

//Parent.vue 
<Child v-on:savevideo="toSaveVideo" v-if="showChild" v-on:close="toClose"/> 
... 
methods:{ 
    toClose:function(){ 
    this.showChild = false; 
    } 
} 

//Child.vue 
<button @click="toAdd">Add</button> 
... 
methods:{ 
    toAdd:function(){ 
    ... 
    let self = this; 
    superagent 
     .get(url) 
     .query({data:data}) 
     .end(function(err,res){ 
     //trigger parent function 
     let resData = res.body.data; 
     self.$emit('savevideo',resData); 
     //'close' should be emitted here! 
    }) 
    this.$emit('close'); //bad code!! This cause the problem! 
    } 
}