elementUI轮播(Carousel)自适应
1.需求:
图片要求宽度100%,高度不能限制死,要求高度自适应。
但这边的问题就是Carousel的高度默认是300px,图片能随着宽度的改变而改变,但Carousel无法改变。
2.解决:
<template>
<div class="three">
<el-carousel arrow="always" :height="bannerHeight+'px'">
<el-carousel-item v-for="it in banner" :key="it.bannerName">
<img ref="bannerImg" :src="it.bannerPath" :alt="it.bannerName" @load="imgLoad" style="width: 100%">
</el-carousel-item>
</el-carousel>
</div>
</div>
</template>
<script>
export default {
data() {
return {
banner: [
{
bannerPath:'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
},
{
bannerPath:'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
},
],
bannerHeight: ""
};
},
mounted() {
this.imgLoad();
window.addEventListener("resize",() => {
this.imgLoad();
},false);
},
methods: {
imgLoad() {
this.$nextTick(() => {
this.bannerHeight =this.$refs.bannerImg && this.$refs.bannerImg.length? this.$refs.bannerImg[0].height: "";//关键的一步
});
}
}
};
</script>
<style lang="less">
.three {
padding: 30px;
width: 100%;
height: 100%;
}
</style>
3.出现了问题:
页面初始化加载的时候,图片还没加载完,最开始没有高度。所以,第一次渲染的时候,文字就上去了,图片就在文字的下面渲染
4.解决:
通过img加载完以后,自己触发onLoad事件,再去设置插件的高度
<template>
<div class="three">
<el-carousel arrow="always" :height="bannerHeight+'px'">
<el-carousel-item v-for="it in banner" :key="it.bannerName">
<img ref="bannerImg" :src="it.bannerPath" :alt="it.bannerName" @load="imgLoad" style="width: 100%" @load=“handleLoad”>
</el-carousel-item>
</el-carousel>
</div>
</div>
</template>
<script>
export default {
data() {
return {
banner: [
{
bannerPath:'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
},
{
bannerPath:'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg'
},
],
bannerHeight: ""
};
},
mounted() {
//this.imgLoad();
window.addEventListener("resize",() => {
this.imgLoad();
},false);
},
methods: {
imgLoad() {
this.$nextTick(() => {
this.bannerHeight =this.$refs.bannerImg && this.$refs.bannerImg.length? this.$refs.bannerImg[0].height: "";//关键的一步
});
},
handleLoad(){
this.imgLoad()
}
}
};
</script>
<style lang="less">
.three {
padding: 30px;
width: 100%;
height: 100%;
}
</style>