项目需求
图片点击下一张,每一张的长宽可能都不一样,比例也不同,期望宽度顶满,高度动态变化
解决思路
el-carousel提供了一个height,不过是固定的,需要自己动态获取图片高度,赋值给走马灯。
注意加载时候,第一张图片需要计算高度
代码
因项目实际需求稍微复杂,此处只贴了部分关键代码
<template>
<el-carousel :height="state.slideHeight+'px'" :autoplay="false" loop indicator-position="outside" ref="carouselRef" @change="slideChange">
<el-carousel-item v-for="(item, index) in state.picList" :key="index">
<img ref="imgRef" :src="item" alt="" />
</el-carousel-item>
</el-carousel>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
const state = reactive({
picList: [] as string[],
slideHeight:500
})
const imgRef=ref();
//跑马灯提供的change事件,会返回当前索引和上一次索引,
//根据索引,每次手动触发时候,动态获取和设置高度
const slideChange=(current:number)=>{
countImgHeight(current);
}
// 获取图片换算后高度,赋值给轮播
const countImgHeight=(index:number)=>{
const img = new Image();
img.onload = function() {
const realHeight = img.height;
const realWidth=img.width;
const height = (Number(realHeight)*轮播宽度)/Number(realWidth);
state.slideHeight=height;
};
img.src=state.picList[index];
}
//初始调用一次
countImgHeight(0);
</script>