微信小程序自定义多选tag组件
效果
maTag.js
// components/myTag/myTag.js
Component({
/**
* 组件的属性列表
*/
properties: {
"list": {
type: Object
},
"one":{
type:Boolean
}
},
ready: function () {
console.log('ready')
var arr=this.data.list
arr.forEach(it=>{
it.show=false
})
console.log(arr);
this.setData({
riderCommentList:arr
})
},
/**
* 组件的初始数据
*/
data: {
riderCommentList: []
},
/**
* 组件的方法列表
*/
methods: {
checkboxChange(e) {
// console.log('checkboxChange e:', e);
let string = "riderCommentList[" + e.target.dataset.index + "].selected"
this.setData({
[string]: !this.data.riderCommentList[e.target.dataset.index].selected
})
let detailValue = this.data.riderCommentList.filter(it => it.selected).map(it => it.value)
// console.log('所有选中的值为:', detailValue)
this.triggerEvent('bindvalue', detailValue)
},
oneChange(e){
// console.log('oneChange e:', e);
this.data.riderCommentList.forEach((it,index)=>{
let s="riderCommentList[" + index + "].selected"
if(it.value==e.target.dataset.value){
this.setData({
[s]: !this.data.riderCommentList[index].selected
})
}
else(
this.setData({
[s]: false
})
)
})
let detailValue = this.data.riderCommentList.filter(it => it.selected).map(it => it.value)
// console.log('所有选中的值为:', detailValue)
this.triggerEvent('bindvalue', detailValue)
},
}
})
myTag.wxml
<view class="comment-btn">
<view
wx:for="{{riderCommentList}}"
wx:for-item="item"
wx:key="index"
bindtap="{{one?'oneChange':'checkboxChange'}}"
data-value="{{item.value}}"
data-index="{{index}}"
checked="{{item.selected}}"
class="btn {{item.selected ? 'btn-selected' : ''}}" >
{{item.title}}
</view>
</view>
myTag.wxss
/* components/myTag/myTag.wxss */
.comment-btn{
display:flex;
flex-wrap: wrap;
}
.btn{
width: 205rpx;
height: 150rpx;
font-size: 24rpx;
padding: 0;
/* border-radius:50rpx; */
border: 1px solid #409EFF;
background: #fff;
color: #409EFF;
border-radius: 4px;
margin: 20rpx 20rpx;
text-align: center;
}
.btn-selected{
/* border: 1px solid #06a380; */
color: #FFF;
background-color:#409EFF;
}
使用时(one是否单选,true为单选,false为多选)
<my-tag list="{{list}}" bind:bindvalue="bindvalue" one="{{false}}"></my-tag>
js
// miniprogram/pagesA/test/test.js
Page({
/**
* 页面的初始数据
*/
data: {
list: [{
value: '1',
title: '选项2'
}, {
value: '2',
title: '选项2'
}]
},
bindvalue(e){
console.log(e.detail)
}
})