vue笔记(六): image图片组件
image组件
没有封装之前,如果图片过大,或者网速过差,未加载完渲染图片之前,图片div就会塌陷,整个页面布局惨不忍睹,加载后,div突然顶起来,又非常突兀,所以封装图片组件是为了后续更好的使用体验
思路
2个img标签,一个在没有传入图片路径时,使用者自定义load占位图,另外一个用来在有图片路径时渲染,如果图片加载报错使用者也可以自定义error占位图
自定义参数
width:图片组件宽度
height:图片组件高度。默认auto
load:默认图片占位图路径
src:图片路径
error:加载错误占位图路径
alt:图片加载错误时的提示文字
新建image.vue
html
<template>
<div class="image" >
<img class="image-img" :src="load" loading="lazy" alt="loading..." v-if="!src">
<img class="image-img" :src="src" :alt="alt" v-if="src" loading="lazy" :onerror="changeImg">
</div>
</template>
<script>
export default{
name: 'Image',
props: {
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: 'auto'
},
load: {
type: String,
default: require('./assets/base.png')
},
src: {
type: String,
default: ''
},
error: {
type: String,
default: require('./assets/img_error.png')
},
alt: {
type: String,
default: '图片'
}
},
methods:{
changeImg(e){
let img = e.srcElement;
img.src = this.error;
img.alt = "加载失败";
img.onerror = null;
}
}
}
</script>
<style scoped>
.image{
display: inline-block;
width: v-bind(width);
height: v-bind(height);
}
.image-img{
width: inherit;
height: inherit;
border-radius: inherit;
}
</style>
<template>
<div class="image" >
<img class="image-img" :src="load" loading="lazy" alt="loading..." v-if="!src">
<img class="image-img" :src="src" :alt="alt" v-if="src" loading="lazy" :onerror="changeImg">
</div>
</template>
<script>
export default{
name: 'Image',
props: {
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: 'auto'
},
load: {
type: String,
default: require('./assets/base.png')
},
src: {
type: String,
default: ''
},
error: {
type: String,
default: require('./assets/img_error.png')
},
alt: {
type: String,
default: '图片'
}
},
methods:{
changeImg(e){
let img = e.srcElement;
img.src = this.error;
img.alt = "加载失败";
img.onerror = null;
}
}
}
</script>
<style scoped>
.image{
display: inline-block;
width: v-bind(width);
height: v-bind(height);
}
.image-img{
width: inherit;
height: inherit;
border-radius: inherit;
}
</style>
调用
html
<div style="padding: 200px;">
<image width="200px"></image>
</div>
<div style="padding: 200px;">
<image width="200px"></image>
</div>
运行结果
本文到此结束。
反馈信息
INFO