uni-app使用swiper切换页面每个滑块高度自适应

bandicam-2020-04-03-18-46-55-287.gif

做音乐播放器小程序时,因为swiper的问题耽误不少时间,总结写目前遇到的问题
1,swiper不给他设置高度有个默认高度,当轮播图使用正好,但是用来做切换每个页面时,每个页面的显示区域(高度)都变成了swiper的高度能显示的区域,这时就要给swiper设置高度,发现设置max-height不起作用,设置min-height和height效果都一样,就是给swiper一个固定的高度,但是,现在每个页面的高度及显示内容区域都写死了,显然是不行的,上网找了几个容器高度根据内容确定的文章发现没什么卵用,用放弃用css实现swiper高度的自适应的幻想。
2,使用js实现容器高度自适应
微信小程序没有dom无法使用js的选择器,不过uni-app提供了一个与querySelecror类似的selectorQuery选择器,使用起来还是有点不习惯,但是,道理都差不多,第一行要写,不用管他为什么,第二行就是选择元素,支持大部分的css选择器,有select是所有元素第一个,selecrAll就是所有选择的元素的集合,这里选择每个页面,给每个页面相同的class用来选择,这个方法返回的信息里有这个页面的高度信息,获取对应的高度设置给swiper,就可以实现高度自适应,即swiper发生变化,页面发生切换,就获取当前页面的高度,放到swiper身上来实现效果
首先是swiper的change事件触发获取页面高度的方法(第一次进入小程序默认第一个页面的高度)

<swiper :style="{'height':swiperHeight+'px'}" class="swiper" :current="currentTab" duration="300" @change="swiperTab">
			<swiper-item>
				<musichall class="component"></musichall>
			</swiper-item>
			<swiper-item>
				<play class="component"></play>
			</swiper-item>
			<swiper-item>
				<musiclist class="component"></musiclist>
			</swiper-item>
		</swiper>
swiperTab(){
			let query = uni.createSelectorQuery().in(this);
				query.selectAll(".component").boundingClientRect();
				console.log(query.select(".component"))
				query.exec((res) => {
					this.swiperHeight = res[0][this.currentTab].height;
					console.log(res[0][this.currentTab].height)
					console.log(res)
				})
			}
export default {
		data() {
			return {
				currentTab: 0,
				swiperHeight:''
			}
		},
		created() {
			this.setSwiperHeight()
		},
		methods: {
			swiperTab(e){
				this.currentTab = e.target.current;
				this.setSwiperHeight()
			},
			//点击切换
			clickTab(e){
				if (this.currentTab == e.target.dataset.current) {
					return false;
				} else {
					this.currentTab = e.target.dataset.current;
					
				};
			},
			setSwiperHeight(){
				let query = uni.createSelectorQuery().in(this);
				query.selectAll(".component").boundingClientRect();
				console.log(query.select(".component"))
				query.exec((res) => {
					this.swiperHeight = res[0][this.currentTab].height;
					console.log(res[0][this.currentTab].height)
					console.log(res)
				})
			}
		},
		components:{
			musichall,
			play,
			musiclist
		}
	}
.swiper{
		height: 550px;
		max-width: 100vw;
	}

注意的是swiper-item中的组件的style样式要设置min-height:100%,设置hright:100%都不行不到为啥
这一写,发现东西不多啊,实现的过程感觉忒煎熬了

发布了117 篇原创文章 · 获赞 146 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/printf_hello/article/details/105298455