我正在使用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;
}
计算属性需要返回从加载函数返回的true或false,但img变量包含jQuery DOM对象,而不是我想要的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;
}
但是这个返回undefined。任何想法如何解决?
答案 0 :(得分:1)
它没有返回状态,因为这是异步的,即使在.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实例的数据部分中定义状态。
答案 1 :(得分:0)
load事件函数的调用是异步的。它的返回值(状态)是未定义的。 解决问题的一种方法是使用回调函数
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;
}
答案 2 :(得分:0)
解决方案是使用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);
});
}