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

  1. 在components文件夹下新建一个名称为tabNormal的文件夹,结构如图:
    在这里插入图片描述
  2. 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>
  1. 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;
}
  1. 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
        })
      }
    }
  }
})
  1. tabNormal组件的index.json代码如下:
{
  "component": true,
  "usingComponents": {}
}
  1. 如果需要在test.wxml的页面中使用tab组件,需要在test文件夹中的test.json里面引入,如下:
"usingComponents": {
    "mp-tabNormal":"../../components/tabNormal/index"
  }
  1. 在test.wxml中使用自定义的mp-tabNormal的元素名
<mp-tabNormal tabTitle="{{tabTitle}}" positionTop="0px" paddingTop="自定义大小,也可以不写,根据自己实际情况">
	<view slot="0">
		tab1的内容
	</view>
	<view slot="1">
		tab2的内容
	</view>
</mp-tabNormal>
  1. 在test.js中写如下代码
  Page({
    data:{
        tabTitle:['tab1','tab2'] //这个tab标题可以写成死的数据,也可以接收后台返回的,写成动态的
    }
  })
  1. 最终效果如图所示:
    在这里插入图片描述
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值