javascriptvue.jsvuejs2emit

Is it possible to execute $emit as synchronous mode and get the result back from emit event


Is it possible to execute as emit as synchronous and get the result back in calling method itself. So, I want to execute next statement after the $emit completed. its as below:

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
}

Solution

  • You shouldnt attempt to make this synchronous. Instead, you might be able to use this idea:

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

    And then in whichever component uses your event:

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