微信小程序 之tab标题组件封装

    技术2023-09-14  86

    在components文件夹下新建一个名称为tabNormal的文件夹,结构如图: tabNormal组件的index.wxml代码如下: <view class="tab" style="position:fixed;left:0;top:{{positionTop}}"> <view wx:for="{{tabTitle}}" wx:key="{{index}}" class="wehx-tabItem {{current==index?'active':''}}" bindtap='toggle' data-index="{{index}}">{{item}}</view> </view> <view class="tab-content" style="padding-top:{{paddingTop}}"> <view wx:for="{{tabTitle}}" class="{{current==index?'show':'hidden'}}"> <slot name="{{index}}"></slot> </view> </view> tabNormal组件的index.wxss代码如下: .tab { display: flex; width: 100%; height: 70rpx; padding-bottom: 18rpx; background-color: #2ea7e0; } .wehx-tabItem { flex: 1; line-height: 70rpx; text-align: center; font-size: 30rpx; color: #96D3EF; } .wehx-tabItem.active { color: #ffffff; position: relative; } .active::after { content: ""; display: block; height: 8rpx; width: 52rpx; background: #ffffff; position: absolute; bottom: 0; left: 0rpx; right: 0; margin: auto; border-radius: 7rpx; } .show { display: block; } .hidden { display: none; } tabNormal组件的index.js代码如下: Component({ /** 1. 组件的属性列表 */ options: { multipleSlots: true //在组件定义时的选项中启用多slot支持 }, properties: { tabTitle: { type: Array, value: [] }, positionTop: { type: String, value: "0" }, paddingTop: { type: String, value: "80rpx" } }, /** 2. 组件的初始数据 */ data: { current: 0 }, lifetimes: { attached() {} }, /** 3. 组件的方法列表 */ methods: { toggle(e) { let that = this if (this.data.current == e.currentTarget.dataset.index) { return false; } else { this.setData({ current: e.currentTarget.dataset.index }) } } } }) tabNormal组件的index.json代码如下: { "component": true, "usingComponents": {} } 如果需要在test.wxml的页面中使用tab组件,需要在test文件夹中的test.json里面引入,如下: "usingComponents": { "mp-tabNormal":"../../components/tabNormal/index" } 在test.wxml中使用自定义的mp-tabNormal的元素名 <mp-tabNormal tabTitle="{{tabTitle}}" positionTop="0px" paddingTop="自定义大小,也可以不写,根据自己实际情况"> <view slot="0"> tab1的内容 </view> <view slot="1"> tab2的内容 </view> </mp-tabNormal> 在test.js中写如下代码 Page({ data:{ tabTitle:['tab1','tab2'] //这个tab标题可以写成死的数据,也可以接收后台返回的,写成动态的 } }) 最终效果如图所示:
    Processed: 0.009, SQL: 9