小程序模板网

微信小程序 扩展组件 tabs 中的 swiper 部分高度自适应

发布时间:2020-05-13 09:52 所属栏目:小程序开发教程

由于官方给了 swiper 固定高度150,且 swiper-item 都是 absolute 定位,所以实际应用中经常会碰到问题,在此记录一下修改方式。

一、正常 npm 下载 tabs 包,并用开发者工具构建 npm

二、修改构建出的目录 miniprogram_npm 目录下的 tabs 插件源码

  • 1、修改 tabs 插件的 wxml 文件,添加 style 属性,看下图位置

  • 2、修改 tabs 插件的 js 文件,添加 swiperStyle 属性

  • 3、使用 tabs 插件的页面添加 swiperStyle 属性,并动态计算高度赋值
<mp-tabs 
  tabs="{{tabs}}" 
  activeTab="{{activeTab}}" 
  swiperClass="weui-tabs-swiper"
  bindtabclick="onTabCLick"
  bindchange="onChange"
  activeClass="tab-bar-title__selected"
  swiperStyle="height: {{tabSwiperHeight}}px"
>
  <block wx:for="{{tabs}}" wx:for-item="tab" wx:for-index="index" wx:key="index">
    <view class="tab-content tab-content-{{index}}" slot="tab-content-{{index}}" >
        {{tab.title}}
    </view>
  </block>
</mp-tabs>
Page({
  data: {
    tabs: [{title: '首页'}, {title: '外卖'}, {title: '商超生鲜'}, {title: '购物'}, {title: '美食饮品'}, {title: '生活服务'}, {title: '休闲娱乐'}],
    activeTab: 0,
    tabSwiperHeight: 0
  },
  tabsSwiperHeight() {
    // tab 组件内的swiper高度自适应问题
    let index = this.data.activeTab;
    let queryDom = wx.createSelectorQuery()
    queryDom.select('.tab-content-' + index).boundingClientRect().exec(rect => {
      this.setData({
        tabSwiperHeight: rect[0].height
      })
    })
  },
  onTabCLick(e) {
    const index = e.detail.index
    this.setData({activeTab: index})
  },
  onChange(e) {
    const index = e.detail.index
    this.setData({activeTab: index})
    this.tabsSwiperHeight();
  }
}


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/25127.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询