如何在出现 v-img 加载错误时显示"image-not-found"图像



看看这个代码笔,了解一个简单的vuetify设置。

https://codepen.io/khoulaiz/pen/gObJPxO?editors=1010

<template>
<div id="app">
<v-app>
<v-content>
<v-container>
<v-row>
<v-col v-for="i in images" :key="i" cols="4">
<v-img max-height="150" max-width="150" :src="i" @error="errorHandler"/>
</v-col>
</v-row>
</v-container>
</v-content>
</v-app>
</div>
</template>
<scritp>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
images: [
"https://via.placeholder.com/150",
"https://via.placeholder.com/doesnotexist",
"https://via.placeholder.com/152"
]
}),
methods: {
errorHandler(url) {
images[1] = "https://via.placeholder.com/151"
this.$forceUpdate()
}
}
})
</script>

中间图像将无法加载。我有一个错误处理程序,我想在其中用工作图像替换失败图像的 src 属性,并且我想在其中强制重新加载图像。

我能够替换失败图像的 src,但我在所有强制重新加载 v-img 的尝试中都失败了。

为什么我没有得到对加载失败的 v-img 的引用?相反,我得到了失败的 url,这无助于我找到失败的元素。:-(

请告诉我,如何强制第二张图像显示备份图像。请注意,图像应该是 v-for 循环的一部分。

您需要通过以下方式访问您的图像this.

errorHandler更改为以下内容应该可以解决问题

errorHandler(url) {
this.images[1] = "https://via.placeholder.com/151"
this.$forceUpdate()
} 

这是我们的 v-img: 用于动态循环

<v-img 
max-height="100%" 
max-width="100%"
:alt="item.name"
:src="item.image ? item.image: require('~/assets/images/img-placeholder.jpg')"
@error="onImageError()" 
>
</v-img>

下面是错误处理程序:

methods: {
onImageError($event) {
event.target.src = require('~/assets/images/img-placeholder.jpg');
},

}

希望它对你有帮助,必须使用$event

您可以使用ref以便轻松访问html对象。像下面一样

<v-col v-for="i in images" :key="i" cols="4">
<v-img max-height="150" max-width="150" :src="i" :ref="'img_' + i" @error="errorHandler(i)"/>
</v-col>

您需要设置唯一的引用并将该唯一引用传递给错误处理程序参数。

从你的错误处理程序中,你可以获取该参数并通过设置新 src 的 ref 检索图像对象 dom

errorHandler(i) {
this.$refs['img_' + i][0].src = "https://via.placeholder.com/151"
}

最新更新