访问jQuery加载返回的数据



我正在开发一个vue.js组件,我得到了这个计算属性:

loading_asset_status(){
var img = $("img.modal-main-image").attr('src', this.current_image.img_url)
.on('load', function() {
return (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0);
});
return img;
}

computed属性需要返回true或false,这是从加载函数返回的,但是img变量包含jQueryDOM对象,而不是我想要的true或false。所以这是行不通的。

我也试过这个:

loading_asset_status(){
var status;
var img = $("img.modal-main-image").attr('src', this.current_image.img_url)
.on('load', function() {
status = (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0);
});
return status;
}

但这个返回未定义。有什么解决办法吗?

它没有返回状态,因为这是异步的,甚至在.on内部的代码仍在执行之前就已经返回了。

然而,您可以设置这样的数据变量:

loading_asset_status(){
var img = $("img.modal-main-image").attr('src', this.current_image.img_url)
.on('load', () => {
this.status = (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0);
});
}

您必须在vue实例的数据部分中定义Where状态。

加载事件函数的调用是异步的。这是因为返回值(状态)未定义。解决问题的一种方法是使用回调函数

loading_asset_status(Callback){
var status;
var lCallback = Callback;
var img = $("img.modal-main-image").attr('src', this.current_image.img_url)
.on('load', function() {
status = (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0);
lCallback (status)
});
return status;
}

解决方案是使用callback函数。

loading_asset_status(function(status){
return status;
});
loading_asset_status(callback){
var status;
var img = $("img.modal-main-image").attr('src', this.current_image.img_url)
.on('load', function(){
status = (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0);
callback(status);
});
}

最新更新