小程序官方本提供了该组件的使用,但是扩展性不太好,为了防止和CheckBox混淆,所以单独剔分出来
一 、HTML
<view wx:for="{{radio}}" wx:key="{{*this}}" class="checkbox '{{item.checked?'checkedActive':''}}'" data-id="{{index}}" bindtap='getradio'>
<text>{{item.value}}</text>
</view>
二、CSS
.checkbox {
display: inline-block;
padding: 10rpx;
background: #eee;
margin: 10rpx;
border-radius: 10rpx;
}
.checkedActive {
background: red;
color: #fff;
}
三、JS
Page({
data:{
radio:[
{ 'value': '北京'},
{'value':'广州'},
{'value':'上海'},
{'value':'沈阳'}
]
},
//单选
getradio:function(e){
let index = e.currentTarget.dataset.id;
let radio = this.data.radio;
for(let i=0; i<radio.length; i++){
this.data.radio[i].checked = false;
}
if (radio[index].checked){
this.data.radio[index].checked = false;
}else{
this.data.radio[index].checked = true;
}
let userRadio = radio.filter((item,index)=>{
return item.checked == true;
})
this.setData({radio:this.data.radio})
console.log(userRadio)
}
})
四、
*选中效果
*选中数据
五、