Javascript 从jQuery加载访问返回的数据

Javascript 从jQuery加载访问返回的数据,javascript,jquery,vue.js,Javascript,Jquery,Vue.js,我正在使用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 == "undefine

我正在使用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变量包含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;
    }

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

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

但是,您可以这样设置数据变量:

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实例的数据部分定义状态。

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

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;
}

解决方案是使用
回调
函数

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);
        });
}

我真的不明白我该怎么办。也许我对这件事的态度是非常错误的。我想要实现的是类似facebook的图像模式,用户可以浏览图库、评论照片等。所有这些都很简单,但我找不到任何其他方式让我的组件知道是否加载了请求的图像。然后我只是v-显示我的加载图标。Vue中是否有更好的方法代替jQuery?@ElDanielo,正如@Saurabh所说,
。在函数上接受
回调
函数
在('load',function()上){
。问题是
返回状态;
是在
加载
方法之前执行的,这就是您接收
未定义
的原因。解决方法之一是使用
回调
函数,如我的答案中所述,或者如@Saurabh在他的答案中所述。@ElDanielo使用我的方法,您可以有一个状态变量,它是c一个变量在开始时可以设置为false,在jquery中可以设置为true。您可以在
v-if
中使用该变量来显示加载图标。