使用
$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>