uniapp中swiper的高度自适应

时间:2025-03-28 10:38:51
<template> <view> <swiper :autoplay="false" @change="changeSwiper" :current="currentIndex" :style="{ height: swiperHeight + 'px' }" > <swiper-item v-for="(item, index) in dataList" :key=""> <view :id="'content-wrap' + index"> 每一个swiper-item的内容区域 .... </view> </swiper-item> </swiper> </view> </template> <script> export default { data() { return { //滑块的高度(单位px) swiperHeight: 0, //当前索引 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 = "#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>