之前开发微信小程序遇到过这个问题,专门去扒了一下当时的解决方案:没有用swiper做这个效果,自定义了tab切换,然后判断层级,显示隐藏对应的列表。原来之前取巧了,哈哈哈哈。

今天记录一下在练习uni-app项目中遇到的tabsSwiper插件使用中又又又遇到这个烦人的高度自适应的问题:

方案一:

scroll-view 里面继续套一个 scroll-view ,设置纵向允许滚动

<swiper class="swiper">
        <swiper-item>
              <scroll-view scroll-y="true" class="scroll">
              <!-- 这里是内容 -->
              </scroll-view>
        </swiper-item>
</swiper>

css中高度设置为100%

.swiper{height: calc(100vh - 120px);}
.scroll{ height: 100%;}

这样就可以实现上下滚动了,唯一不好的就是:他是在一个swiper的盒子里面纵向滚动,并不是我们想要的全屏纵向滚动,如下图:

小程序swiper高度自适应解决方案-QUI-Notes

方法二:

js动态计算高度,然后再绑给swiper,然后,页面加载时计算一下第一个的高度,点击切换时再计算一下高度,这样的好处就是,每个都可以撑满,而不像第一种情况一样,在盒中盒内滚动;

html:

<swiper class="swiper" :style="{height:swiperHeight + 'px'}" :current="current" @change="changeCurrent">
    <swiper-item :class="'swiper0'+index" >
      <!-- 这里是内容 -->
    </swiper-item>
</swiper>

js:

export default {
        data() {
        return {
            swiperHeight:0, //外部的高度
            current:0
        }
    },
    onLoad() {
                this.getElementHeight('.swiper' + this.current)
        },
    methods:{
        //点击tab切换
        changeCurrent(index) {
            this.current = index;
            this.getElementHeight('.swiper' + this.current)
        },
        //动态获取高度
        getElementHeight(element) {
            //一定要 this.$nextTick 完成之后在获取dom节点高度
            this.$nextTick(()=>{
                let query = uni.createSelectorQuery().in(this);
                query.select(element).boundingClientRect(data => {
                    console.log(data.height);
                    this.swiperHeight = data.height;
                }).exec()
            })
        }
    }
}

这个效果可能需要自己调整,例如swiper-item的高度不能为0,不然这个swiper还是无法撑开高度,可以f12找到有高度的最外成盒子,把:class="'swiper0'+index" 绑在这个元素身上,这样就有高度了。

小程序swiper高度自适应解决方案-QUI-Notes

当然这上面的两种方法不是我想的,大神原地址:https://www.jianshu.com/p/04e00dee221d。其中还提到另外一种方案,插件,算了小程序不适合用插件!