最近项目中遇到实现设备多选的需求,虽然这个需求很常见,但功能需求的不同,实现过程也大相径庭,我们的需求时只提供子级选择,父级不做选择,只提供层级显示;
el-tree是elementPlus的组件,熟悉的都知道这个UI库,对如传入的数据格式也是固定,对与本次需求,后端返回的数据需求做指定:
const defaultProps = {children: 'data',label: 'name',
}
el-checkbox结合el-tree实现多选功能,具体代码实现如下:
<el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
<el-tree class="tree" :data="deviceLevel" :props="defaultProps" show-checkbox node-key="ids" :default-expand-all="true" check-strictly :default-checked-keys="[5, 6]" @check-change="testCheckChange" ref="testingTree" />
我们后端接收到的数据传入字符串形式,所以在选择中直接处理了;用的正则的原因是去掉出现零是我情况;
// 实现树形选择联动功能
function testCheckChange(data, checked, node) {queryParams.DeviceidArr = useUnique(queryParams.DeviceidArr)if (checked) {queryParams.DeviceidArr = queryParams.DeviceidArr.concat(",", data.id).replace(/,0,/g, ',').replace(/,0/g, ',').replace(/0,/g, ',')let arr = queryParams.DeviceidArr.split(",").map(item => Number(item)).filter(item => item !== 0);// 使用Set对象去重 let uniqueArr = [...new Set(arr)];if (uniqueArr.length == nodeId.value.length) {// 取消全选状态显示checkAll.value = true}} else {// 防止在字符串和数组之间转换出现零的情况let arr = queryParams.DeviceidArr.split(",").map(item => Number(item)).filter(item => item !== 0);let indexToRemove = arr.indexOf(data.id);if (indexToRemove !== -1) {arr.splice(indexToRemove, 1);}if (arr.length !== nodeId.value.length) {// 取消全选状态显示checkAll.value = false}queryParams.DeviceidArr = arr.join(",")}
}
//全选按钮勾上的方法事件
function handleCheckAllChange(params) {if (params) {allNode.value = []nodeId.value = []hierarchicalIteration(deviceLevel.value)testingTree.value?.setCheckedKeys(allNode.value);let uniqueArr = [...new Set(nodeId.value)];queryParams.DeviceidArr = uniqueArr.join(",")}else {//取消全选时置空testingTree.value.setCheckedKeys([])queryParams.DeviceidArr = ''}
}