2017-09-05 94 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! 
    } 
}