dht-img | 替代原有的img标签功能,组件本身的宽高都由最外层容器所决定,支持图片加载失败处理 | src | String | src本地图片需要require | |||
fit | String | cover | |||||
alt | String | 加载失败 | 当最终还是加载失败的时候 | ||||
error-src | String | 输入的情况下载alt之前,如果错 误处理图片能加载成功则加载错误 成功图片 |
|||||
lazy | Boolean | FALSE | 是否启用图片懒加载 |
这个功能比较耗时,但是也算顺利写出来了,代码挺low的,并且也没有定义加载过程中图片或者文字代替。但是这样我也比较满意了。
并且增加了图片懒加载,懒加载的本身是直接支持单个元素的。只有在页面当中展示了才会加载图片。
代码部分
<template>
<div class="dht-Image" @click="lazyImg">
<img
ref="dht_img"
class="dht-showimg"
:style="{ objectFit: fit }"
v-if="isload"
:src="lazy === true ? lazyList.img : src"
:alt="alt"
@error="imgErr"
@load="imgSuccess"
/>
<div v-else class="dht-errImgInfo">
<img
ref="dht_img2"
class="dht-showimg"
:style="{ objectFit: fit }"
v-if="errload"
:src="lazy === true ? lazyList.errimg : errorSrc"
:alt="alt"
@error="imgErr2"
@load="imgSuccess2"
/>
<span v-else>{{ alt }}</span>
</div>
</div>
</template>
<script>
export default {
name: "dhtImg",
props: {
lazy: {
type: Boolean,
default: false
},
src: {
type: String,
default: ""
},
//最终失败提示
alt: {
type: String,
default: "图片加载中……"
},
//错误图片
errorSrc: {
type: String,
default: ""
},
fit: {
type: String,
default: "cover"
}
},
filters: {},
watch: {
//需要实时监听数据变化,否则单纯数据变化,不会重新显示图片
src() {
this.isload = true;
},
errorSrc() {
this.errload = true;
}
},
data() {
return {
//图片是否加载成功
isload: true,
//错误图片是否加载成功
errload: true,
//计时器
time: null,
//懒加载图片展处
lazyList: {
img: "",
errimg: ""
}
};
},
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {
//是否懒加载展示图片
this.lazy && this.lazyImg();
},
methods: {
//懒加载函数
lazyImg() {
//启动之前先清理之前的定时器
clearInterval(this.time);
//获得当前元素
let dom = this.$refs.dht_img;
//判断元素是否显示
let isElementInViewport = el => {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
rect.right <=
(window.innerWidth || document.documentElement.clientWidth)
);
};
this.time = setInterval(() => {
//当元素显示则停止计时器
isElementInViewport(dom) && this.stopLazyImg();
}, 1000);
},
//停止计时器,让图片显示
stopLazyImg() {
clearInterval(this.time);
//console.log("该展示图片了,并且定时器也要停止。");
//注意让元素图片状态重新变化
this.isload = true;
this.errload = true;
this.lazyList = {
img: this.src,
errimg: this.errorSrc
};
},
//img成功
imgSuccess() {
this.isload = true;
},
//img错误加载判断
imgErr() {
let img = this.$refs.dht_img;
img ? (img.onerror = null) : ""; //控制不要一直跳动
this.isload = false;
},
imgSuccess2() {
this.errload = true;
},
imgErr2() {
let img2 = this.$refs.dht_img2;
img2 ? (img2.onerror = null) : ""; //控制不要一直跳动
this.errload = false;
}
}
};
</script>
<style lang="scss">
@import "../style/common/let_style";
.dht-Image {
width: 100%;
height: 100%;
.dht-showimg {
@extend .dht-Image;
}
.dht-errImgInfo {
width: 100%;
height: 100%;
font-size: 12px;
color: $font_info;
display: flex;
align-items: center;
justify-content: center;
}
}
</style>