[英]Change image source (twice) when src does not exist
I just started using Vue in the front-end of my website . 我刚开始在网站的前端使用Vue 。 In one of my Vue-components I want an image with a certain path:
在我的Vue组件之一中,我想要具有一定路径的图像:
<img src="path/example/with/vue/var">
Now, this is what I want to do: 现在,这就是我想要做的:
- Check if the file in "path/example/with/vue/var" exists
检查“ path / example / with / vue / var”中的文件是否存在
- If not: Change the src to "another/path/with/vue/var"
如果不是,请执行以下操作:将src更改为“ another / path / with / vue / var”
- Check if "another/path/with/vue/var" exist
检查是否存在“另一个/路径/具有/ vue / var”
- If not: Change the src to "default/path"
如果不是:将src更改为“ default / path”
I already tried to use onerror
with a function inside of it. 我已经尝试过将
onerror
与内部函数一起使用。 But the problem is I'm loading 100+ objects with a couple of images for each object. 但是问题是我正在加载100个以上的对象,并且每个对象有几个图像。 If I just check if the file exists the normal way(through Ajax or with an XMLHttpRequest), the performance is completely gone.
如果我只是检查文件是否存在正常方式(通过Ajax或XMLHttpRequest),则性能将完全消失。 All objects are loaded through a JSON file.
所有对象均通过JSON文件加载。
I hope you guys understand the question. 我希望你们能理解这个问题。
I suggest you to use https://imagesloaded.desandro.com/ 我建议您使用https://imagesloaded.desandro.com/
You can understand if the path exist in this way 您可以了解路径是否以这种方式存在
$('#container').imagesLoaded()
.always( function( instance ) {
console.log('all images loaded');
})
.done( function( instance ) {
console.log('all images successfully loaded');
})
.fail( function() {
console.log('all images loaded, at least one is broken');
})
In the Fail function you can re-make imagesLoaded() for another path and so on 在Fail函数中,您可以为另一个路径重新创建imagesLoaded(),依此类推。
An easy way to implement this would be to make a component out of the object you are using in your v-for
loop. 一种简单的实现方法是使组件在
v-for
循环中使用的对象之外。
Then you can simply used a computed property to check the src
property on your object. 然后,您可以简单地使用计算属性来检查对象的
src
属性。
in this case you do: 在这种情况下,您可以:
const image = new Image()
And then set the src like so: 然后像这样设置src:
image.src = <object>.src
After you have set the src on the Image object you could then check if your specified image has loaded with onload
or has failed with onerror
. 在Image对象上设置src之后,可以检查指定的图像是否已加载
onload
或因onerror
失败。
I do something similarly in my code by check if an image has loaded or not so I can replace the placeholder image with the actual loaded image: 我通过检查图像是否已加载来在代码中执行类似的操作,因此可以将占位符图像替换为实际加载的图像:
setImagePlaceholder(hotel) {
this.$set(hotel, 'imgLoaded', false);
const image = new Image();
image.src = hotel.thumbUrl;
image.onload = () => {
hotel.imgLoaded = true;
};
}
Don't know how I could make it any easier for you. 不知道我该如何简化您的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.