简言
今天从张老师那里学到了图片加载错误后显示兜底图和提示文字的用法。用vue实现下图片组件。
代码
思路: 图片加载失败,添加错误css类,添加伪类填充错误图片和alt提示信息。
<template>
<img
:class="{ is__error: isOnloadError }"
:src="src"
:alt="alt"
class="image"
@error.once="errorEvent"
/>
</template>
<script lang="ts" setup>
import {
ref } from 'vue'
const isOnloadError = ref(false)
const props = defineProps({
src: {
// 图片路径
type: String,
default: () => ''
},
alt: {
// 文字提示
type: String,
default: () => ''
}
})
// 加载错误事件
const errorEvent = () => {
isOnloadError.value = true
}
</script>
<style lang="scss" scoped>
.image.is__error {
position: relative;
display: inline-block;
width: 100px;
height: 100px;
}
.image.is__error::before {
content: attr(alt);
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 30px;
line-height: 30px;
text-align: center;
color: #fff;
background-color: rgba($color: #000000, $alpha: 0.6);
z-index: 2;
}
.image.is__error::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url('@/assets/images/error/img_error.jpg') center no-repeat;
}
</style>
效果
结语
结束了。实现时也可以使用全局自定义指令来实现错误图片和提示信息的显示。