在我司的后台项目中遇到通过 Cascader 级联选择器 选择组织发起对象的情况。
给有同样需求的入坑人员提供一个解决的思路:
效果如下:
要求是点击最末尾的子节点可以单选,但同时点击父节点又要可以选中包括父节点在内的子节点。
代码如下:分为 HTML, data(),和methods()三块来写:
1.HTML 代码如下:
<!-- 下拉多选框 -->
<el-form-item label="发起对象:">
<el-cascader
ref="cascader"
:options="options"
:props="optionProps"
clearable
@change="handelChange()"
></el-cascader>
</el-form-item>
//options: 可选项数据源,键名可通过 Props 属性配置
//props :配置选项。具体看 element-ui。
2. data()中如下
data() {
return {
temp: { //页面中的其他数据
title: "",
deadTime: "",
groupId: "", //组织ID
groupName: "", //组织名
},
options: [], //options用于接受接口传递过来的组织数据
optionProps: { //optionsProps用于配置选项。
value: "id",
label: "groupName",
children: "children",
multiple: true, //是否多选
},
};
},
3.methods()中如下:
通过接口 getTreeList获取组织数据,记得在 mounted()中调用parentCateChange()获取组织数据
parentCateChange() {
// 获取数据
getTreeList().then((res) => {
this.options = res.data; //将组织数据存在options[]中
});
},
handelChange(val) { //点击事件,选中节点的时候调用
let nodesInfo = this.$refs["cascader"].getCheckedNodes(true);
console.log("nodesInfo>>>>>", nodesInfo); //可以打印看现在调用了哪个节点
let groupNameList = [], //定义两个数组用来存放组织名和组织ID
groupIdList = [];
nodesInfo.map((item) => { //通过map循环出组织数据的 id和 name 存入数组中
groupNameList.push(item.label);
groupIdList.push(item.value);
});
this.temp.groupId = groupIdList.join(",");
this.temp.groupName = groupNameList.join(",");
},
//以上在数据库中使用英文逗号分开的,但也有用JSON数据的格式,以下写出 JSON数据的格式,
//数据要求如下:
// string (query) 上报对象json[{"unitId":"xxx","unitName":"xxx"}]
// 添加单位多选
handelChange(val) {
const nodesInfo = this.$refs["cascader"].getCheckedNodes(true);
console.log("nodesInfo>>>>>", nodesInfo);
const groupList = [];
nodesInfo.map((item) => {
groupList.push({
unitId: item.value,
unitName: item.label,
});
});
this.temp.reportTarget = JSON.stringify(groupList);
},
通过 ref 的 cascader 拿到数据,getCheckedNodes()是 element-ui 中的方法,用于选择点击的子节点。然后打印出目前点击的子节点的数据。创建groupNameList,groupIdList的空数组。通过map遍历数据,将选中的子节点的id(value)和label(组织名)压入到空数组中。然后将数据压入到数据库中。
PS:对父子节点是否相关联的有要求的,在 :props(此处为 optionProps[ ]中)添加checkStrictly :true/false ,并修改getCheckedNodes(true/false)