uniapp的checkbox多选框限制最大选择数量
直接上代码,复制粘贴就可以看效果
<template>
<view>
<checkbox-group @change="checkboxChange">
<view v-for="(item, ind) in optionList" :key="item.id" class="selectItem" style="">
<view style="float: left;" v-if="(maxSelect > 0 &&maxSelect ==Object.keys(selectedItem).length)">
<checkbox @click="checkboxTips()" :disabled="item.name|selectName" :value="item.name" />
</view>
<view style="float: left;" v-else>
<checkbox :value="item.name" />
</view>
<view>{{item.name}}</view>
</view>
</checkbox-group>
</view>
</template>
<script>
let thatOne;
export default {
data() {
return {
selectedItem: {},
maxSelect: 2,
optionList: [{
id: 1,
name: "小英"
},
{
id: 2,
name: "小张"
},
{
id: 3,
name: "小红"
},
{
id: 4,
name: "小明"
}
],
}
},
beforeCreate: function() {
thatOne = this;
},
filters: { //设置最大可选
selectName(name) {
if (thatOne.maxSelect > 0 &&
thatOne.maxSelect == Object.keys(thatOne.selectedItem).length) {
for (var t in thatOne.selectedItem) {
if (t == name) {
return false
}
}
return true
} else {}
return false
},
},
methods: {
checkboxTips() {//多选提示
if (
thatOne.maxSelect == Object.keys(thatOne.selectedItem).length) {
uni.showToast({
title: "做多选择" + thatOne.maxSelect + "项",
icon: "none"
})
}
},
//多选
checkboxChange: function(evt) {
var objectA = {}
var arr = []
for (let i = 0; i < this.optionList.length; i++) {
for (let j = 0; j < evt.target.value.length; j++) {
if (this.optionList[i].name === evt.target.value[j]) {
var objectB = this.optionList[i];
this.$set(objectA, evt.target.value[j], objectB)
arr.push(this.optionList[i].id)
break;
}
}
}
this.selectedItem = objectA;
},
}
}
</script>
<style scoped>
.selectItem {
width: 100%;
margin-left: 30upx;
margin-top: 50upx;
}
</style>
效果


浙公网安备 33010602011771号