以下代码引用了一个组件函数,该函数从 url 获取数据并尝试将该数据设置为属性。它不起作用,似乎 this
无法从 ajax clousure 范围访问。
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);
}
});
}
...
}
})
如何使this
可访问?
最佳答案
您需要.bind
this
上下文,因为在组件的上下文中不会自然地调用回调:
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
});
}
// ...
});
您可以在此处了解有关 .bind
的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
关于jquery - 在 Ajax 函数中访问 Vue.js 组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132872/