1、知其所以然:
为什么要对swiper高度进行动态设置?因为swiper对高度进行了限制,如果你不对高度进行设置会出现如下图效果,导致swiper无法占满屏幕,列表内容显示不全。
2、下面来看看具体要实现的效果,效果页面如下:
从下图可以知道我们要计算的swiper高度是绿色框部分。
所以,绿色框高度 = 紫色 - 红色 - 黑色;
明确思路了,下面我们分部计算出各颜色框的高度:
1)紫色 :
直接使用uni-app的API获取屏幕可见区域的高度,在这里即紫色区域的高度。
let windowHeight = uni.getSystemInfoSync().windowHeight;//页面可见区域
2)红色:
直接使用uni-app的API uni.createSelectorQuery方法可以获取指定view的高度,这里在红色区域使用
<view class="view_head"> </view>,便可以直接使用下面的方法获取其高度
var query = uni.createSelectorQuery();
query.select('.view_head').boundingClientRect(rect => {
if (rect) {
console.log("view_head.height = "+rect.height)
}
}).exec();
3)黑色高度,我这边定义了44px,你也可以使用2)方法获取。
3、具体代码实现
1、在布局设置高度为动态赋值
<swiper class="tab-swiper" @change="switchTag" :current="nowActive" :style="'height: ' + height +'px;'">
</swiper>
2、在data声明height函数
data() {
return {
height: 750,
}
},
3、在页面挂载后设置swiper高度
mounted() {
this.setHeight();
},
4、设置高度
setHeight() {
let windowHeight = uni.getSystemInfoSync().windowHeight;//页面可见区域
console.log("windowHeight = "+windowHeight)
windowHeight = windowHeight - 44;//页面可见区域 - 在线购物条高度
console.log("windowHeight = "+windowHeight)
var query = uni.createSelectorQuery();
query.select('.view_head').boundingClientRect(rect => {
if (rect) {
console.log("view_head.height = "+rect.height)
this.height = windowHeight - rect.height;//页面可见区域 - 头部高度
console.log("this.height = "+this.height)
}
}).exec();
},