功能实现:
el-tree树多选,将选中的树对象中某个字段值改为true,并过滤出所有为true的对象,组成新的数组提交给后端
<template>
<div>
<!-- 树形菜单 -->
<el-tree
:data="stageList"
show-checkbox
default-expand-all
node-key="id"
ref="tree"
highlight-current
:props="defaultProps"
@check-change="handleNodeClick"
></el-tree>
<!-- 确定按钮和自定义操作 -->
<div class="action-bar">
<el-button type="primary" @click="handleSubmit">确定</el-button>
<el-button @click="customAction">自定义操作</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
stageList: [
{
children: [
{
children: null,
choose: false,
createDept: 1,
createTime: "2025-02-19 14:20:28",
createUser: 2,
description: "child1",
id: 6,
isDeleted: 0,
name: "child1",
parentId: 5,
status: 0,
updateTime: "2025-03-19 16:40:21",
updateUser: 147238244,
useStatus: 1,
vaildStatus: null,
},
],
choose: false,
createDept: 1,
createTime: "2025-02-19 14:20:28",
createUser: 2,
description: "father3",
id: 5,
isDeleted: 0,
name: "father3",
parentId: 0,
status: 0,
updateTime: "2025-03-19 16:40:21",
updateUser: 147238244,
useStatus: 1,
vaildStatus: null,
},
],
defaultProps: {
children: "children",
label: "name",
},
filteredList: [], // 存储过滤后的结果
};
},
created() {
// 数据加载完成后设置选中状态
this.$nextTick(() => {
const checkedKeys = this.getCheckedKeys(this.stageList);
this.$refs.tree.setCheckedKeys(checkedKeys);
});
},
methods: {
// 递归收集选中节点ID
getCheckedKeys(nodes) {
let keys = [];
if (!nodes) return keys;
nodes.forEach(node => {
if (node.choose) {
keys.push(node.id);
}
if (node.children && node.children.length > 0) {
keys = keys.concat(this.getCheckedKeys(node.children));
}
});
return keys;
},
// 处理节点选中状态变化
handleNodeClick(data, checked) {
this.updateChoose(data, checked); // 更新选中节点及其子节点的 choose 字段
},
// 递归更新节点及其子节点的 choose 字段
updateChoose(data, value) {
data.choose = value;
if (data.children && data.children.length > 0) {
data.children.forEach((child) => {
this.updateChoose(child, value);
});
}
},
// 点击确定按钮时过滤出 choose 为 true 的节点
handleSubmit() {
this.filteredList = this.filterSelected(this.stageList);
console.log("Filtered List:", this.filteredList); // 打印过滤后的结果
},
// 递归过滤出 choose 为 true 的节点
filterSelected(list) {
const result = [];
list.forEach((item) => {
if (item.choose) {
result.push(item);
}
if (item.children && item.children.length > 0) {
result.push(...this.filterSelected(item.children));
}
});
return result;
},
// 自定义操作
customAction() {
console.log("Custom action triggered");
// 在这里实现自定义操作逻辑
},
},
};
</script>
<style>
.action-bar {
position: fixed;
bottom: 20px;
right: 20px;
}
</style>
代码说明
-
handleNodeClick
方法:- 当节点选中状态变化时触发。
- 调用
updateChoose
方法,将当前节点及其子节点的choose
字段设置为true
或false
。
-
updateChoose
方法:- 递归地更新节点及其子节点的
choose
字段。
- 递归地更新节点及其子节点的
-
handleSubmit
方法:- 点击确定按钮时调用。
- 调用
filterSelected
方法,过滤出choose
为true
的节点,并存储到filteredList
中。
-
filterSelected
方法:- 递归地遍历树形数据,将
choose
为true
的节点过滤到新数组中。
- 递归地遍历树形数据,将
-
customAction
方法:- 自定义操作逻辑,可以根据需求实现。
-
样式调整:
- 使用
position: fixed
将操作栏固定在界面右下角。
- 使用
至此完成!!!
测试有效!!!感谢支持!!!