是否可以以同步模式执行$emit并从emit事件中获取结果

use*_*357 4 javascript emit vue.js vuejs2

是否可以像同步一样执行并在调用方法本身中获取结果。所以,我想在 $emit 完成后执行下一条语句。其如下:

Parent component has method, 
                 doCustomValidation();

child component is as follow:
methods:
{
  Save: function(){
 // Can I get the response here from parent component and then, execute 
    doGenericValidation ?

 var errorFields = this.$emit('custom-validation');  
   doGenericValidation(errorFields);   //this is generic validations
}
Run Code Online (Sandbox Code Playgroud)

Fla*_*ame 10

您不应该尝试使其同步。相反,您也许可以使用这个想法:

methods: {
    myMethod() {
        // Pass a function as a parameter.
        this.$emit('custom-validation', this.onComplete);
    },
    onComplete() {
        // Do stuff after custom-validation has completed.
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在任何使用您的事件的组件中:

<some-component @custom-validation="doStuff" />
<script>
...
methods: {
    doStuff(done) {
        // Your logic here. After that, call the callback function.
        done();
    }
}
...

Run Code Online (Sandbox Code Playgroud)