$emit is not emitting the message to parent from inside axios

Viewed 3845

I have a method in child component which is responsible to get the data from server and after receiving the data, i am trying to emit the data to parent. The below method is from Vue.component (child). The problem is, parent component is not able to receive the emitted data. Just to check, I moved the $emit code outside axios request call, then it is working. If i $emit from inside axios, it is not working.

Not working (emit from inside axios):

methods:{
    methodName: function(){
        let self = this;
        axios.get('url')
        .then(function(response){
            if (response.data.res) {
                console.log('response is true, i can see this message');
                self.$emit('updateparentdata',response.data);
            }
        });
        self.$emit('close');
    }
},

Working (emit from outside axios):

methods:{
    methodName: function(){
        let self = this;
        self.$emit('updateparentdata','some dummy data');
        axios.get('url')
        .then(function(response){
            if (response.data.res) {

            }
        });
        self.$emit('close');
    }
},

This is my component code in my html page, if something is emitted from updateparentdata, then it will call 'updateData' function in parent vue.

<modal 
    v-if="showModal"
    @close="showModal = false"
    v-on:updateparentdata="updateData">
</modal>

This is my method in parent vue,

updateData: function(response){
    console.log(response);
},

This method is not triggered after i emitted the data from child component. If i emit data outside axios, then this method is called, but if i emit data from inside axios, this method is not called.

3 Answers

as @RubanrajRavichandran mentioned in his Solution 1 where self = this its because in the axios .then the this changes. you can instead use arrow function like .then((response) => {} and this will work so you don't have to use self

Related