自定义组件:
自定义组件脚本:
WXML:
<view class='tab-control'>
<!-- 遍历最好使用block -->
<block wx:for="{{titles}}" wx:key="{{inde}}x">
<view class='tab-item {{currentIndex == index ? "active":""}}' bind:tap="handleItemClick" data-index="{{index}}"><text>{{item}}</text></view>
</block>
</view>
WXSS:
.tab-control{
display: flex;
height: 88rpx;
line-height: 88rpx;
background: orange;
}
.tab-item{
flex: 1;
text-align: center;
}
.active{
color:red;
}
.active text{
border-bottom: 6rpx solid red;
padding: 20rpx 10rpx;
}
JS:
Component({
/**
* 组件的属性列表
*/
properties: {
titles:{
type:Array,
value:{}
}
},
/**
* 组件的初始数据
*/
data: {
currentIndex:0
},
/**
* 组件的方法列表
*/
methods: {
// 监听的所有方法都要写在此处
handleItemClick(event) {
// 1、获取传入的index
const index = event.currentTarget.dataset.index;
// 2、改变记录的currentIndex,将其对应的位置通过三目运算符加上active
this.setData({
currentIndex:index
})
// 3、发出自定义组件,通知页面内部的点击事件
this.triggerEvent('itemclick',{index,title:this.properties.titles[index]},{})
}
}
})
传入其他页面: