微信小程序swiper组件高度自适应内容的问题

    科技2022-07-14  137

    需要在开发中使用一个选项卡,选择了

    微信开放文档-小程序-扩展能力-扩展组件 tabs,

    将需要的内容插入插槽。由于内容高度不固定这就要求 tabs自适应内容高度。

    解决思路

    动态的获取内容的高度把高度值传给组件

    一、 怎样获取内容的高度

    分析观察发现,所有的内容必须放到class="tab-content"的view中,获取view的高度,由于这个属性的view有可能有多个所以对应的高度值有很多,所以就把他们放到一个数组中。
    <view class="tab-content" slot="tab-content-{{index}}"></view>

    在引用组件的页面index. js文件中

    onLoad: function () { let heightArr=new Array() wx.createSelectorQuery().selectAll(".tab-content").boundingClientRect( res=>{res.forEach(res=>{ console.log(res.height) heightArr.push(res.height) }) this.setData({heightArr:heightArr}) } ).exec() },

    二、 怎样把获取到的高度传递给组件呢,

    组件中有swiperClass 属性可以传递高度,但是要在css中写从js中获取的值,不知道怎么写就放弃了这个方法了(有会的小伙伴教我一下)。下面是给组件添加高度属性

    给组件另外添加一个高度属性

    style="height: {{height}}rpx;" // 在组件的wxml文件中swiper标签中加入

    tabs组件 wxml文件中:

    <view class="weui-tabs"> <view>。。。省略导航菜单。。。</view> <swiper class="{{swiperClass}}" style="height: {{height}}rpx;" //加入这句 current="{{activeTab}}" duration="{{duration}}" bindchange="handleSwiperChange"> <swiper-item wx:for="{{tabs}}" wx:key="title"> <slot name="tab-content-{{index}}"></slot> </swiper-item> </swiper> </view>

    tabs组件 js文件中:

    height:{type:Number,value:''}, //在组件js文件properties中加入 properties: { tabs: { type: Array, value: [] }, tabClass: { type: String, value: '' }, swiperClass: { type: String, value: '' }, height:{type:Number,value:''}, activeClass: { type: String, value: '' }, tabUnderlineColor: { type: String, value: '#07c160' }, tabActiveTextColor: { type: String, value: '#000000' }, tabInactiveTextColor: { type: String, value: '#000000' }, tabBackgroundColor: { type: String, value: '#ffffff' }, activeTab: { type: Number, value: 0 }, swipeable: { type: Boolean, value: true }, animation: { type: Boolean, value: true }, duration: { type: Number, value: 500 } },

    三、 现在可以直接给组件添加高度属性了

    需要注意的是,我们得到的heightArr是一个数组,这数组的排列顺序和swiper-item 的顺序一致,下表也是从零开始,根据swiper的 current属性(当前所在滑块的 index ),当前显示那个swiper-item 我们就取那个下标的高度传递给组件。tabs组件中有个属性 active-tab (激活 tab 索引 ),这样我们也可以动态的改变下标了

    在引用组件的页面index. wxml文件中

    <mp-tabs tabs="{{tabs}}" activeTab="{{activeTab}}" swiperClass="weui-tabs-swiper" activeClass="headline" tabUnderlineColor="var( --weui-TAG-TEXT-BLUE)" height="{{(heightArr[activeTab]+20)*(750/windowWidth)}}" //添加高度属性 bindtabclick="onTabCLick" bindchange="onChange"> <view class="tab-content" slot="tab-content-{{index}}">。。。省略内容。。。</view> </mp-tabs>

    四、 别忘了添加两个事件,点击和滑动时来改变activeTab值,

    在引用组件的页面index. js文件中

    onTabCLick(e) { const index = e.detail.index this.setData({activeTab: index}) }, onChange(e) { const index = e.detail.index this.setData({activeTab: index}) }, *** 注:在js获取的值是px,需要转换成rpx *** px转换rpxrpx= px*(750/屏幕宽度)rpx转换pxpx= rpx*(屏幕宽度/750)
    Processed: 0.010, SQL: 8