需要在开发中使用一个选项卡,选择了
将需要的内容插入插槽。由于内容高度不固定这就要求 tabs自适应内容高度。
在引用组件的页面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() },给组件另外添加一个高度属性
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 } },在引用组件的页面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>在引用组件的页面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)