问题:如何处理多个相同的select不允许重复选择的情况?
在使用多个select选择框时,我们可能会遇到这样的情况:同一份数据集多个select选择框中不能选择相同的项。这时我们可以利用computed属性和自定义的函数来控制每个select选择框中可选项的禁用状态,从而达到限制重复选择的目的。

代码实现:
例如,在Vue组件中借助computed属性实现select选择框的禁用状态控制:
<el-select v-model="value1" placeholder="请选择">
<el-option v-for="item in haha" :key="item.id" :label="item.label" :value="item.id" :disabled="disabledChoose(item)"></el-option>
</el-select>
<el-select v-model="value2" placeholder="请选择">
<el-option v-for="item in haha" :key="item.id" :label="item.label" :value="item.id" :disabled="disabledChoose(item)"></el-option>
</el-select>
<el-select v-model="value3" placeholder="请选择">
<el-option v-for="item in haha" :key="item.id" :label="item.label" :value="item.id" :disabled="disabledChoose(item)"></el-option>
</el-select>
...
computed: {
disabledChoose(item) {
return function(item) {
let findItemIndex = [this.value1, this.value2, this.value3].findIndex(item2 => item2 == item.id);
let newArr = [this.value1, this.value2, this.value3].splice(findItemIndex, 1);
return newArr.includes(item.id);
}
}
},
上述代码中,我们通过computed属性中的disabledChoose函数来控制每个item是否被disabled(禁用),函数中通过参数item来判断当前的item是否已被选中,从而确定其disabled状态,达到限制重复选择的目的。
问题:如何在多个select中限制重复选择相同的数据?
当我们在同一页面动态循环出多个select时,需要实现的功能是:每当某一项被选择后,其他的select中对应的项就变为禁用状态,以限制重复选择相同的数据。
代码实现:
比如,在Vue组件中通过computed属性和自定义的函数实现限制重复选择相同数据的实现方式如下:
<Select v-model="parItem.id" @on-change="onChangeProgram">
<Option v-for="(subItem,idx) in programList" :key="subItem.id" :data-index='idx'
v-show="parItem.id == subItem.id || !selectIdsArr.includes(subItem.id)" :value="subItem.id">{{subItem.name}}</Option>
</Select>
...
data() {
return {
parArr:[
{guid:'ffffddd',id:null,},
{guid:'eeeee',id:null,},
{guid:'ffff',id:null,}],
selectIdsArr:[],
programList:[
{"id":1,"name":"选项1"},
{"id":2,"name":"选项2"},
{"id":3,"name":"选项3"},
],
}
},
methods: {
onChangeProgram() {
this.selectIdsArr = [];
for (const item of this.parArr) {
if (item.id) {
this.selectIdsArr.push(item.id);
}
}
},
},
以上就是关于限制重复选择的两种实现方式,它们分别基于computed属性和自定义函数来解决问题,在实际应用中可以根据不同的场景选择合适的实现方式。
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7132.html
