遇到的问题
-
问题:
uni-app开发小程序,使用swiper组件时内容高度不固定,需要动态获取高度;使用uni.createSelectorQuery()方法获取一直为null,且切换swiper时不能动态切换高度;
这里swiper的数据是动态渲染的(静态数据时不存在这个问题)
-
原因:
- 1.uni.createSelectorQuery()获取一直为null
- 检查是否使用$nextTick包裹
- 如包裹后仍获取不到可再尝试增加延时器setTimeout
- 2.切换swiper时不能动态切换高度
- 可将swiper-item中的内容使用scroll-view包裹
- 1.uni.createSelectorQuery()获取一直为null
解决
-
实现代码
<!-- .vue页面文件 --> <template> ... <!-- swiper组件,只展示了核心代码配置 --> <swiper :style="'height:'+ plateHeight +'px;'" :current="hotPlateActive" @change="plateSwiperChange"> <swiper-item v-for="(p,pindex) in hotPlateData" :key="pindex"> <scroll-view v-if="pindex === hotPlateActive"> <view class="new" id="plateHeight">......</view> </scroll-view> </swiper-item> </swiper> ... </template> <script> export default { data(){ hotPlateData: [...], // swiper数据 hotPlateActive: 0, // 选中的项 plateHeight: null, // swiper的高度 }, ... onLoad() { this.getData() }, methods: { getData() { // 获取swiper数据 ...... // 动态获取高度 self.$nextTick(() => { setTimeout(function() { // 获取模块的高度 let query1 = uni.createSelectorQuery() query1.select("#plateHeight").boundingClientRect() query1.exec(res => { if (self.utils.IsExis(res[0])) { self.plateHeight = res[0].height } }) }, 10); }) }, // 切换swiper plateSwiperChange(e) { var self = this self.hotPlateActive = e.detail.current self.$nextTick(() => { setTimeout(function() { // 获取板块天梯模块的高度 let query1 = uni.createSelectorQuery() query1.select("#plateHeight").boundingClientRect() query1.exec(res => { if (self.utils.IsExis(res[0])) { self.plateHeight = res[0].height } }) }, 10); }) }, } }