相关文章推荐
慷慨大方的皮带  ·  vue3+ts:shims-vue.d.ts·  4 周前    · 
稳重的保温杯  ·  npm ERR! errno 1 npm ...·  5 月前    · 
英姿勃勃的酱牛肉  ·  Java ...·  8 月前    · 
深情的小摩托  ·  Ruby on Rails ...·  1 年前    · 

使用 $refs 属性获取元素的引用,然后通过 clientHeight offsetHeight 属性获取元素的高度:

<template>
  <div ref="element">Dynamic Height Element</div>
</template>
<script>
export default {
  mounted() {
    // 获取元素高度
    const height = this.$refs.element.offsetHeight;
    console.log(height);
</script>

使用 v-bind:style 绑定样式,并在样式中计算元素高度。这种方式需要在更新元素数据时手动触发重新计算:

<template>
  <div :style="{ height: dynamicHeight }">Dynamic Height Element</div>
</template>
<script>
export default {
  data() {
    return {
      dynamicHeight: 'auto'
  mounted() {
    // 更新元素高度
    this.dynamicHeight = this.$refs.element.clientHeight + 'px';
</script>

使用第三方库 like vue-awesome-swiper 中的 autoHeight 选项,它可以为滑块容器内的每个滑块计算出高度并自适应容器高度:

<template>
  <swiper :options="swiperOptions">
    <swiper-slide>Slide 1</swiper-slide>
    <swiper-slide>Slide 2</swiper-slide>
    <swiper-slide>Slide 3</swiper-slide>
  </swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
export default {
  components: {
    Swiper,
    SwiperSlide
  data() {
    return {
      swiperOptions: {
        autoHeight: true
</script>
 
  •