uniapp中的swiper组件可以用来做滑动切屏,由于必须设置一个固定高度,然而在每一个swiper-item里的内容高度不一样,就会造成内部的内容不能自动撑开
<template>
<view>
<swiper
:autoplay="false"
@change="changeSwiper"
:current="currentIndex"
:style="{ height: swiperHeight + 'px' }"
>
<swiper-item v-for="(item, index) in dataList" :key="item.id">
<view :id="'content-wrap' + index">
内容....
</view>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default {
data() {
return {
//swiper滑块的高度(单位px)
swiperHeight: 0,
//swiper当前索引
currentIndex: 0,
//列表数据
dataList: [],
};
},
onLoad(args) {
//动态设置swiper的高度
this.$nextTick(() => {
this.setSwiperHeight();
});
},
methods: {
//手动切换题目
changeSwiper(e) {
this.currentIndex = e.detail.current;
//动态设置swiper的高度,使用nextTick延时设置
this.$nextTick(() => {
this.setSwiperHeight();
});
},
//动态设置swiper的高度
setSwiperHeight() {
let element = "#swiperCon" + this.currentIndex;
let query = uni.createSelectorQuery().in(this);
query.select(element).boundingClientRect();
query.exec((res) => {
if (res && res[0]) {
this.swiperHeight = res[0].height;
}
});
},
},
};
</script>