Element Plus 走马灯自动高度配置的笨办法

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>
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇