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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With