Access Vue.js component property inside Ajax function
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
As already answered, .bind
will fix the issue on this, however, I like to use a different approach, and store this
in a variable before any Ajax calls or nested functions. Very helpful when your code grows inside the method. It is also easier to read.
You can save this
to a var called self
for example. Then use self
anywhere inside that method without a problem.
var MyComp = Vue.extend({
props: {
html_prop: null,
},
// ....
fetchCondiciones: function(url){
var self = this;
$.ajax({
type: "GET",
url: url,
cache: false,
data: vardata,
success: function(data,status,error) {
if(data != ''){
self.html_prop = data;
}
}
error: function(data,status,error){
alert(error);
}
});
}
// ...
});
UPDATE:
Today we could just use ES6 arrow function syntax.
The value of this
inside the function is determined by the surrounding scope, and there is no need to create a new variable, or to use bind
:
// ....
fetchCondiciones: url => {
$.ajax({
type: "GET",
url: url,
cache: false,
data: vardata,
success: (data,status,error) => {
if(data != ''){
this.html_prop = data;
}
}
error: (data,status,error) => {
alert(error);
}
});
}
Or:
// ....
fetchCondiciones(url) {
$.ajax({
type: "GET",
url: url,
cache: false,
data: vardata,
success(data,status,error) {
if(data != ''){
this.html_prop = data;
}
}
error(data,status,error) {
alert(error);
}
});
}