1. 使用 uni.createSelectorQuery() 获取节点信息
2. 使用 uni.getSystemInfo() 获取当前可使用窗口高度
3. 使用 v-bind 动态修改 swiper 高度
实现代码:
html 部分:
<view :style="{height: swiperHeight + 'px'}" >
<swiper
style="height: 100%"
:current="cardIndex"
@change="changeQuestion"
>
<swiper-item v-for="item in lists" :key="item.id">
<uni-card class="etmHights">
{{item.title}}
</uni-card>
</swiper-item>
</swiper>
</view>
script 部分 :
<script setup>
import { ref , getCurrentInstance , onMounted} from 'vue'
const instance =getCurrentInstance()
// 动态设置高度
const swiperHeight=ref(800)
// 窗口高度
const windowHeight=ref()
// 获取元素高度
function getItemHeight(){
let query = uni.createSelectorQuery().in(instance);
query.select(".etmHights").boundingClientRect(data => {
// 如果 窗口高度 - (顶部距离 + 底部距离 )小于 100 则 元素本身高度 + 100
if ( windowHeight.value - (data.top + data.bottom) < 100 ) {
swiperHeight.value=data.height + 100
}
// 如果 窗口高度 - (顶部距离 + 底部距离 )大于 100 则 元素本身高度 加 剩余高度
if (windowHeight.value - (data.top + data.bottom) > 100) {
swiperHeight.value = data.height + (windowHeight.value -
(data.top + data.bottom))
}
}).exec();
}
onMounted(async()=>{
uni.getSystemInfo({
success(res) {
// console.log('可使用窗口高度',res.windowHeight);
windowHeight.value=res.windowHeight
},
})
setTimeout(() => {
getItemHeight()
}, 800);
})
// 切换事件
const changeQuestion = (e) => {
getItemHeight()
}
</script>