element tree选父节点所有子节点选中,选子节点父节点选中

时间:2025-03-28 14:39:30
<template> <div class="cm"> <el-row v-loading="loading"> <el-col :span="24" :xs="24" style="height: 550px;overflow-y: auto;"> <el-tree ref="tree" :data="data" :props="props" show-checkbox node-key="menuId" :check-strictly="true" :default-checked-keys="array" @check="clickDeal"> </el-tree> </el-col> <el-col :offset="4" :span="6" class="mt20"> <el-button @click="getCheckedKeys" size="mini" type="primary">提交</el-button> </el-col> </el-row> </div> </template> <script> import {roleMenu,roleMenuUpdate} from "@/api/"; export default { props: ["permissionRoleId"], components: {}, watch: {}, data() { return { loading: false, data: [], props: { label: "name", children: "children", }, checkedId:[], count: 1, array:[] }; }, created() { this.initMe(); }, updated () { // 给多选树设置默认值 this.$refs.tree.setCheckedKeys(this.array) }, methods: { clickDeal(currentObj, treeStatus) { // 用于:父子节点严格互不关联时,父节点勾选变化时通知子节点同步变化,实现单向关联。 let selected = treeStatus.checkedKeys.indexOf(currentObj.menuId) // -1未选中 // 选中 if (selected !== -1) { if(currentObj.children && currentObj.children.length!=0){ // 子节点只要被选中父节点就被选中 this.selectedParent(currentObj) // 统一处理子节点为相同的勾选状态 this.uniteChildSame(currentObj, true) } } else { // 未选中 处理子节点全部未选中 if (currentObj.children && currentObj.children.length !== 0) { this.uniteChildSame(currentObj, false) } } }, // 统一处理子节点为相同的勾选状态 uniteChildSame(treeList, isSelected) { this.$refs.tree.setChecked(treeList.menuId, isSelected); if (treeList.children && treeList.children.length!=0) { for (let i = 0; i < treeList.children.length; i++) { this.uniteChildSame(treeList.children[i], isSelected) } } }, // 统一处理父节点为选中 selectedParent(currentObj) { let currentNode = this.$refs.tree.getNode(currentObj) if (currentNode.parent.key !== undefined) { this.$refs.tree.setChecked(currentNode.parent, true) this.selectedParent(currentNode.parent) } }, handleCheckChange(data, checked, indeterminate) { }, handleNodeClick(data) { }, //获取树形的数据 initMe() { var that = this; var data = { roleId: this.permissionRoleId, }; this.loading = true; roleMenu(data).then((res) => { if(res.code == 200){ this.loading = false; that.data = res.data.sysMenusList; var tempdata = res.data.sysMenusList; var array = []; function deep(val) { if (!val.children) { if (val.checked == "true") { array.push(val.menuId); } } else { for (var i = 0; i < val.children.length; i++) { if (val.checked == "true") { array.push(val.menuId); } deep(val.children[i]); } } } for (var k = 0; k < tempdata.length; k++) { var tempDeep = deep(tempdata[k]); } this.array = array; }else{ this.$message({ type:"error", message:res.message }) } }); }, //保存提交 getCheckedKeys() { var data = { menu: this.$refs.tree.getCheckedKeys(), roleId: this.permissionRoleId } console.log('提交数据',data) }, }, }; </script>