Search code examples
vuejs2vue-componentlaravel-spark

this.$http.get is not working inside methods vue js


I am working with Laravel + spark + vue js.

Blade file

<draggable class="col-md-12" :list="emergencies" :element="draggableOuterContainer" @end="onEnd">

Js file

import draggable from 'vuedraggable'
module.exports = {
data() {        
    return {
        emergencies:[]
    };
},
components: {
    draggable,
},
created() {
    this.getEmergencies();
},
methods: {
    getEmergencies() {
        this.$http.get('/ajax-call-url')
            .then(response => {
                this.emergencies = response.data;
            });
    },        
    onEnd: function(evt){
        var counter = 1;
        this.emergencies.forEach(function(user, index) {
            this.$http.get('/ajax-call-url/')
            .then(response => {   
            });    
            counter++;  
        });
    }
}
};

Here I have drag and Drop, On Drop, I call "onEnd" function and getting following error.

TypeError: this is undefined

Here this.emergencies.forEach is working but it is giving error on this.$http.get

Any suggestions, what can be the solutions?


Solution

  • Instead of using function syntax, use arrow functions, as scope of this changes inside function:

    onEnd: function(evt){
        var counter = 1;
        this.emergencies.forEach((user, index) => {
            this.$http.get('/ajax-call-url/')
            .then(response => {   
            });    
            counter++;  
        });
    }
    

    Check this for explanation.