繁体   English   中英

Vue.js $ emit没有在回调时触发父函数

[英]Vuejs $emit didn't trigger parent's function on callback

我的问题就是这样的: Vuejs $ emit不会在callback上触发 但是我在项目中使用了超级代理。 这是我的代码:

//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放到回调之外时,一切都很好。 为什么$ emit事件不会在回调中触发?

好的,我知道了。

“ v-if”绑定在子组件上。

因为在我的项目中,子组件中还有另一个触发器“关闭”以关闭此子组件,并且该触发器在回调之外发出,因此引起了问题。

//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!
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM