Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Vue.js component property inside Ajax function

The following code refers to a component function which fetches data from an url and tries to set that data to a property. It's not working, seems like this is not accessible form the ajax clousure scope.

var MyComp = Vue.extend({
props: {
        html_prop: {}
        ....
},
methods: {
        fetchCondiciones: function(url){

            $.ajax({
                    type: "GET",
                    url: url,
                    cache: false,
                    data: vardata ,
                    success: function(data,status,error) {
                        if( data!=''){
                            this.html_prop = data;
                        }
                    },
                    error: function(data,status,error){
                        alert(error);
                    }
            });

        }

        ...
    }
})

How could I make this accessible?

like image 737
javier_domenech Avatar asked May 10 '16 08:05

javier_domenech


1 Answers

You need to .bind the this context, as the callback is not naturally called in the context of the component:

var MyComp = Vue.extend({
props: {
        html_prop: null,
},
        // ....
        fetchCondiciones: function(url){

            $.ajax({
                    type: "GET",
                    url: url,
                    cache: false,
                    data: vardata,
                    success: function(data,status,error) {
                        if(data != ''){
                            this.html_prop = data;
                        }
                    }.bind(this), // bind this here
                    error: function(data,status,error){
                        alert(error);
                    }.bind(this) // bind this here
            });

        }

        // ...
});

You can learn more about .bind and this here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

like image 159
nils Avatar answered Oct 04 '22 02:10

nils