由于项目需要,频繁使用到按钮组,如图所示,
后期优化代码时,提炼出了自定义的子组件。
难度虽不大,但也是自己码出来的,转载请注明,谢谢~
效果如下图:
父组件:
<!--button-group/button-group.wxml-->
<view class="btn-group-wrap">
<view wx:for="{{dataList}}" wx:for-item="item" wx:for-index="index" :key="index" class="btn-item {{currentId===item.id ? 'select' : ''}} {{dataList.length===1?'only-btn':''}}" data-id="{{item.id}}" bindtap="switchBtn">
<!-- 如果需要的话也可加icon -->
<!-- <icon type="success" class="icon-test" size="20"/> -->
<!-- <text wx:if="{{item.icon}}" class="iconfont icon-{{item.icon}}"></text> -->
<text wx:if="{{item.text}}" class="btn-text">{{item.text}}</text>
<text wx:if="{{!item.text}}" class="btn-text">按钮{{index+1}}</text>
</view>
</view>
// button-group/button-group.js
Component({
/**
* 组件的属性列表
*/
properties: {
dataList:{
type:Array,
value:[]
},
currentId:{
type:String,
value:''
},
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
switchBtn:function(e){
console.log(e.currentTarget.dataset.id,'子组件currentId')
this.setData({
currentId:e.currentTarget.dataset.id
})
var btnEventDetail = {
currentId:e.currentTarget.dataset.id
} // detail对象,提供给事件监听函数
var btnEventOption = {} // 触发事件的选项
this.triggerEvent('btnEvent', btnEventDetail, btnEventOption)
}
}
})
/* button-group/button-group.wxss */
.btn-group-wrap {
box-sizing:border-box;
width: 100%;
height: auto;
display: flex;
flex-wrap: wrap;
align-items: stretch;
justify-content: center;
margin: 20rpx auto;
}
.btn-item {
flex: 1;
align-items: center;
line-height: 50rpx;
height: 26px;
font-size: 26rpx;
text-align: center;
border: 1px solid #bbb;
border-right:0;
background-color: #fff;
}
.btn-item:first-child {
border-radius: 30rpx 0 0 30rpx;
}
.btn-item:last-child {
border-radius: 0 30rpx 30rpx 0;
border-right: 1px solid #bbb;
}
.btn-text {
display: inline-block;
padding: 0 20rpx;
text-align: center;
}
.only-btn {
border-radius: 30rpx!important;
}
.select{
background-color: #3287F0;
color: #ffffff;
border-color: #3287F0;
}
.icon-test {
height: 23px;
vertical-align: middle;
}
父组件:
<view class="page">
<button-group currentId="0" dataList="{{btnList}}" bind:btnEvent="btnEvent"></button-group>
</view>
const app = getApp()
Page({
data: {
btnList:[
{
id:'0',
text:'',
icon:''
},
{
id:'1',
text:'',
icon:''
},{
id:'2',
text:'',
icon:''
}
]
},
onLoad: function () {
},
onReady(){
this.btnGroup = this.selectComponent("#btn-group")
},
btnEvent(e){
// 按钮点击触发,接收子组件传过来的数据,进行操作
console.log(e.detail,'e')
}
})