VUE 使用IView 中的Select进行分组(OptionGroup)展示,允许多选情况下组内元素不能多选功能只允许单选功能实现;
实现思路
根据on-select 和on-change返回值不同,并且on-select的返回优先于on-change的返回时间的原理,得到本次选中的元素和本次返回的结果。在根据当前选中的id找到当前元素的兄弟元素,将除过自己的兄弟元素从选中的集合中删除,从而达到组内单选的效果
页面布局
<Select v-model="model.TypeTagArry" multiple @on-select="TypeTagSelect" @on-change="TypeTagChange">
<OptionGroup :label="item.TypeName" v-for="item in TypeTagList" :key="item.ID">
<Option v-for="info in item.ChildList" :value="info.ID" :key="info.ID">{{ info.TypeName }}</Option>
</OptionGroup>
</Select>
全局变量代码
data() {
return {
TypeTagList:[],//模型分类维度数据
TypeTagAll:[],select分组数据,ID PID 格式的数据源
TypeTagID:0,//当前选择的分类维度数据
}
},
选中和改变事件
TypeTagChange(value){
//根据当前选中的id找到当前元素的兄弟元素,将除过自己的兄弟元素从集合中删除,从而达到单选的效果
if(this.TypeTagID != 0){
var _this = this;
if(this.model.TypeTagArry.length > 1 && this.TypeTagID > 0){
var index = this.model.TypeTagArry.indexOf(this.TypeTagID);
if(index > -1){
//查找当前选项的对象
var list = this.TypeTagAll.filter(function(e){ return e.ID == _this.TypeTagID; });
//根据当前对象的父级筛选出所有的兄弟元素。
list = this.TypeTagAll.filter(function(e){ return e.PID == list[0].PID; });
list.forEach(function(info,i){
//从已选择的数据中去除掉已选择的兄弟元素
var index = _this.model.TypeTagArry.indexOf(info.ID);
if(index >= 0 &&_this.model.TypeTagArry.length > 0 && _this.TypeTagID != info.ID){
_this.model.TypeTagArry.splice(index, 1);
}
});
}
}
}
this.TypeTagID = 0;
this.$forceUpdate();
},
TypeTagSelect(obj){
//select返回的当前选中的元素。
this.TypeTagID = obj.value;
}