Element Plus 的走马灯(carousel)元素是提供了 height="auto" 这个方法,让走马灯的高度可以根据子内容的高度自动设置。但是经过研究之后,我发现它只能够识别写死在 <el-carousel-item> 元素属性上的高度。不太好用。
而且假如说走马灯滚动的时候,它自身的高度还会变化,这就导致网页不稳定了。这是一种不合理的设计。
因此,我的需求是让走马灯的高度固定为其最高的子元素的高度。经过一番测试,我最终找到了“笨办法”,也许手段比较简单,但是能用。
具体实现
在走马灯内部的子组件上设置监听元素高度,回传到父组件上,然后设定走马灯高度。
父组件:
<template>
<div>
<h2>{{ data.name }} <span v-for="color in data.color" :style="{ color: color }">●</span></h2>
<el-carousel
:height="carouselHeight + 'px'"
:autoplay="!statVisible"
:interval="5000"
:arrow="data.length === 1 ? 'never' : 'always'"
ref="carousel"
>
<el-carousel-item
class="video min-h-[450px]"
v-for="video of data"
:key="video.video.link"
>
<VideoInfo v-bind="video" @send-height="handleHeight" ></VideoInfo>
</el-carousel-item>
</el-carousel>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import VideoInfo from './VideoInfo.vue';
import { ElCarousel, ElCarouselItem } from 'element-plus';
// ============== 控制走马灯高度 ===========
const carousel = ref<HTMLElement>()
const carouselHeight = ref<number>(450)
function handleHeight(value: any) {
carouselHeight.value = value + 30
}
</script>
VideoInfo 子组件:
<template>
<div class="flex flex-col items-center video-info" ref="box">
<img :src="video.cover" />
</div>
</template>
<script setup>
import { onMounted, ref, useTemplateRef, nextTick } from 'vue';
// =========== 回传高度 ===============
const box = useTemplateRef('box')
const emits = defineEmits(['send-height'])
onMounted(async () => {
console.log(box.value)
await nextTick()
emits('send-height', box.value.offsetHeight)
})
</script>