One of the events that an HTML element can have is the error
event: (MDN Web Docs)
The error event occurs when a resource fails to load or cannot be used. This could happen if a script encounters an error during execution or if an image cannot be found or is invalid.
Implementing this event is straightforward: (demo)
<script setup lang="ts">
import { ref } from 'vue';
const num = 4;
const show = ref(new Array(num + 1).fill(true)); // using "of" in v-for, index starts from 1
function handleError(index) {
show.value[index] = false;
}
</script>
<template>
<template v-for="index of num">
<div v-if="show[index]">
<img :src="`/images/${index}.png`" @error="handleError(index)" />
</div>
</template>
</template>
If you are using Vite and your images are located within the project (and can be imported as URLs), there is another method with improved performance: (demo)
<script setup lang="ts">
function getImages() {
// All images are under `./images` and have the extension `.png`
const original = import.meta.glob('./images/*.png', {
eager: true,
import: 'default',
});
const transformed = Object.entries(original)
.map(([key, value]) => [
key.replace('./images/', '').replace('.png', ''),
value,
]);
return Object.fromEntries(transformed);
}
const images = getImages();
</script>
<template>
<div v-for="(path, index) in images" :key="index">
<img :src="path" />
</div>
The first method involves attempting to load each image dynamically and excluding any items that fail to load.
The second method entails importing the URLs of all images at compile time and displaying them based on their actual URLs. This approach allows determining the images during build time, resulting in better performance.