如果项目中有需要使用到级联选择器,但是要限制选择个数,可以用watch监听级联选择器双向绑定的数组。
1.组件默认数据绑定
级联选择器默认会绑定一个数组,节点的显示文本和值分别对应label、value属性,节点的后代对应children属性。
options为默认绑定的数组,v-model绑定的chooseList数组中是所有选中的value值
-
expandTrigger:参数可以实现悬停展开效果
-
emitPath :设置为false,只返回该节点的值
-
multiple:设置为true,支持多选
<el-cascader
v-model="editForm.jingangvo.cellList"
:options="functionNameptions"
:props="[multiple:true,emitPath;false,expandTrigger: "hover']
@change="getcascader
ref="cascader'
clearable
2.指定数据绑定
:props=“{label:‘name’,value:‘id’,children:‘son’ }”
3.watch监听v-model绑定的数组,控制选中个数
watch:{
'editForm.jingangvo.cellList':{
deep:true,
handler(newVal,oldval){
if(newval.length>5){
this.$message.error("最多只支持选择5项')
this .$nextTick(()=>{
this.editForm.jingangvo.cellList=oldval
})
}
}
}
}
4.前后端数据转换,实现回显
页面初始化加载,选择器中v-model绑定的数组有正确的值,就能回显;但是后端获取的是一个数组对象,对象中包含value和label,我们需要把value拿出来放在一个新数组里面
(1)接口初始数据回显
...
//调接口
let res = await this.GETINNERENTERPRISECONFIG(invitationCode);
//接口返回的级联选择器绑定的数据
console.log("接口返回的级联选择器绑定的数据 ,res.jingangvo.cellList)
//将数组中的value值取出重新赋值,级联选择器就可以回显啦!
res.jingangvo.celllist = res.jingangv0.cellList.map(item=>item.value)
console.log("将接口数据转成组件回显需要的value数组",res.jingangvo.cellList)
this.editForm=res
(2)重新选择级联选择器后,如何将选择的数据转换成后端需要的数据
getcascader(e){
//e是选择的value,labels是选择时一级和二级的label
//const checkedNodes=this .$refs.cascader .getcheckedNodes();
//const labels=checkedNodes .map(node=>node.label);
if(e.length<=5){
this.switchCascader(e)
}
},
switchCascader(e){
//找到初始级联选择器中所有的childern
const childrenList = this.functionNameOptions.map(item=>{
return item.children
}
)
//遍历选中的e数组中的value,找到children中包含value的数组对象
let newsCellList =[]
e.forEach(item=>{
let valueItem = item
childrenList.forEach((item)=>{
newsCellList.push(item,filter(item=>item.value===valueitem))
})
})
//去除newsCellList里面的空数组
newsCellList= newsCellList.filter(arr=>arr.length>0)
//每个数组里面嵌套了一个数组,将里层数组去掉
this.cancatArr = newsCellList.map(item=>item[0])
return this.cancatArr
}
-
接口需要的数据格式:
(3)最后提交数据给后端的时候,如何处理级联选择器的数据?
这里又要分两个思路:
1.没有重新选择级联选择器,还是默认的后端返回的初始数据,但是返回的数据被我们初始化页面的时候改变了,所以需要调取后端需要的数据转换方法,再将初始数据转换一次。
2.重新选择了级联选择器,就直接将重新选择的数据转换后再赋值传给后端
submit(){
if(this.editForm.jingangV0.celllist,length==0) return this,$message.error("请选择级联选择器')
if(this.cancatArr.length>0){
//如果重新选择过级联选择器,那this.cancatArr就有值,直接赋值
this.editForm.jingangv.cellList = this.cancatArr
}else{
//没有重新选择,用的初始默认值,因为一开始我们将数据转换了级联选择器需要的value值数据,所以需要将数据再转换一次接口所需要的格式
this,editForm.jingangv0.celllist = this,switchCascader(this,editForm.jingangV0.celllist)
}
}