二次封装el-image多图预览

58 阅读1分钟

image.png

二次封装el-image

src\components\previewImg\index.vue

<template>
    <!-- 图片预览 -->
    <div class="box">
        <div v-for="(item, index) in srcList" :key="index" :class="[{'img': !showErrorTxt, 'img_slot': showErrorTxt }]">
            <el-image  
                class="img_in"
                :src="item"
                :preview-src-list="srcList"
                ref="previewImg"
                @error="handleError"
            >
                <!-- 加载失败的处理 -->
                <div slot="error">{{ errorTxt }}</div>
            </el-image>
        </div>
    </div>
</template><script>
export default {
    props: {
        imgUrl: { //图片列表
            type: Array,
        },
        errorTxt: { // 错误提示信息
            type: String,
            default: '加载失败'
        }
    },  
    data() {
        return {
            srcList: [], // 列表
            showErrorTxt: false, // 返回的显示文件提示
        }
    },
    mounted() {
        this.generateUrl(this.imgUrl);
    },
    watch: {},
    methods: {
        generateUrl(imgUrl) { // 处理展示列表的图片路径
            let url = '';
            imgUrl.forEach((id) => {
                url = id;
                this.srcList.push(url);
            });
        },
        handleError() { // 图片显示错误的处理
            this.showErrorTxt = true;
        }
    }
};
</script>
<style lang="scss" scoped>
.box {
    display: flex;
    align-items: center;
}
​
.img {
    width: 180px;
    height: 170px;
    margin-right: 10px;
    cursor: pointer;
}
​
.img_in {
    width: 100%;
    height: 100%;
    object-fit: cover; // 保持比例填充容器
}
​
.img_slot {
    width: auto;
    height: 20px;
}
</style>
​
​

应用:

<previewImg :imgUrl="imgUrl" />
​
data() {
    return {
        imgUrl: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F961438b8-5a20-4f7f-b37b-958a3da6b698%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1758272429&t=d4db17338b9472fc0a932b963abd7ae6', 'https://img0.baidu.com/it/u=987683691,2912972555&fm=253&app=138&f=JPEG?w=800&h=800','https://img2.baidu.com/it/u=3844699936,1913541897&fm=253&app=138&f=JPEG?w=800&h=800']
    }
}
​