uniapp中的swiper組件可以用來做滑動切屏的,但是有個不好的地方,就是必須設(shè)置一個固定的高度,對于在每一個swiper-item里的內(nèi)容可能不一定的情況,就會造成內(nèi)部的內(nèi)容不能自動撐開,就被截取了,這個就很頭疼,網(wǎng)上找了很多資料,終于解決了這個問題。
一、解決思路
- 在每次滑動切換的時候,動態(tài)地獲取swiper-item內(nèi)部的DOM的元素的高度。
- 將獲取的高度動態(tài)設(shè)置給swiper元素。
二、代碼解析
<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">
每一個swiper-item的內(nèi)容區(qū)域
....
</view>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default {
data() {
return {
//滑塊的高度(單位px)
swiperHeight: 0,
//當(dāng)前索引
currentIndex: 0,
//列表數(shù)據(jù)
dataList: [],
};
},
onLoad(args) {
//動態(tài)設(shè)置swiper的高度
this.$nextTick(() => {
this.setSwiperHeight();
});
},
methods: {
//手動切換題目
changeSwiper(e) {
this.currentIndex = e.detail.current;
//動態(tài)設(shè)置swiper的高度,使用nextTick延時設(shè)置
this.$nextTick(() => {
this.setSwiperHeight();
});
},
//動態(tài)設(shè)置swiper的高度
setSwiperHeight() {
let element = "#content-wrap" + 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>
<style lang="scss">
</style>