这周用uniapp做的一个小程序有个需求就是做一个可滑动的tab选项卡,但是遇到一个问题就是swiper的高度是固定的,要么就是给定一个高度值,这样就不能满足我的需求,我需要向上滑动来请求更多的数据,给定高度那么后面的数据就隐藏掉了。
想了一下能不能在swiper-item里面嵌入一个scroll-view,在触底后触发事件@scrolltolower="lowerBottom"和下拉刷新数据@refresherrefresh="getFresh"请求数据渲染展示,但是查了一下这个好像容易出问题,所以就没使用这个方法,有兴趣的可以使用一下看看有没有坑。
后来查到了一种解决方法就是直接使用swiper然后动态更改高度来让数据展示。 下面是大概的代码实现一下
<template>
<view>
<swiper
:autoplay="false"
@change="changeSwiper"
:current="currentIndex"
:style="{ height: swiperHeight + 'px' }"
>
<swiper-item>
<view class="list">
每一个swiper-item的内容区域
<view v-for="(item, index) in dataList" :key="item.id"></view>
....
</view>
</swiper-item>
</swiper>
</view>
</template>
<script>
export default {
data() {
return {
//滑块的高度(单位px)
swiperHeight: 0,
//当前索引
currentIndex: 0,
//列表数据
dataList: [],
};
},
created() {
//动态设置swiper的高度
this.setWiperHeight()
},
methods: {
//手动切换题目
changeSwiper(e) {
this.currentIndex = e.detail.current;
//动态设置swiper的高度,使用nextTick延时设置
this.$nextTick(() => {
this.setSwiperHeight();
});
},
//动态获取设置swiper的高度
setSwiperHeight() {
let query = uni.createSelectorQuery().in(this);//uni-app提供了一个与querySelecror类似的selectorQuery选择器
query.selectAll(".list").boundingClientRect();//selecrAll就是所有选择的元素的集合,这个方法返回的信息里有这个页面的高度信息,获取对应的高度设置给swiper,就可以实现高度自适应
query.exec((res) => {
this.swiperHeight = res[0][this.currentIndex].height;
})
},
},
};
</script>
大概就是这样,然后这个我好像发现了一个问题就是首次加载第一个默认tab时获取设置的swiper高度好像不太准确,因为我后面切换tab时看默认tab的数据跟首次加载的是有点不同的,但差距不大。但目前好像没有更好的办法就只能先这样了。