siteTree.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <div class="overflow-auto">
  3. <Tree
  4. v-if="processedTreeData.length"
  5. :tree-data="processedTreeData"
  6. :default-expand-all="true"
  7. :virtual="false"
  8. :show-icon="true"
  9. @select="selectHandler"
  10. >
  11. <template #icon="scope">
  12. <Icon v-if="scope.selected" icon="material-symbols:circle" color="green" />
  13. <Icon v-else-if="scope.leaf && scope.selectable" icon="material-symbols:circle" />
  14. <Icon
  15. v-else-if="scope.leaf && !scope.selectable"
  16. icon="material-symbols:circle"
  17. color="red"
  18. />
  19. </template>
  20. </Tree>
  21. <p v-else>暂无数据</p>
  22. </div>
  23. </template>
  24. <script setup lang="ts">
  25. import { ref, watch } from 'vue';
  26. import { Tree } from 'ant-design-vue';
  27. import { MonitorSiteTreeNode } from '@/api/sys/model/monitorModel';
  28. import { TreeNode } from '../types/siteTree';
  29. import Icon from '@/components/Icon/Icon.vue';
  30. // props & emits
  31. const props = defineProps<{ treeData?: MonitorSiteTreeNode }>();
  32. const emit = defineEmits<{ select: [value: MonitorSiteTreeNode] }>();
  33. const processedTreeData = ref<TreeNode[]>([]);
  34. const expandedKeys = ref<string[]>([]);
  35. // 递归处理树节点并格式化为需要的格式,将父节点记录到指定数组中
  36. function walk(node: MonitorSiteTreeNode, parentNodeKeys: string[]): TreeNode {
  37. // 在这里赋值
  38. const res: TreeNode = {
  39. title: node.label,
  40. key: node.id,
  41. selectable: !!node.display,
  42. leaf: !!node.leafNode,
  43. raw: node,
  44. children: [],
  45. };
  46. if (node.children) {
  47. // 记录所有的父节点id
  48. parentNodeKeys.push(node.id);
  49. node.children.forEach((child) => {
  50. res.children.push(walk(child, parentNodeKeys));
  51. });
  52. }
  53. return res;
  54. }
  55. function selectHandler(_, { selectedNodes }) {
  56. if (selectedNodes.length) {
  57. emit('select', selectedNodes[0]?.raw);
  58. }
  59. }
  60. // 更新逻辑在这里
  61. watch(
  62. () => props.treeData,
  63. (v) => {
  64. if (!v) return;
  65. expandedKeys.value = [];
  66. processedTreeData.value = [walk(v, expandedKeys.value)];
  67. },
  68. {
  69. immediate: true,
  70. },
  71. );
  72. defineExpose({
  73. processedTreeData,
  74. expandedKeys,
  75. });
  76. </script>
  77. <style scoped>
  78. ::v-deep(.vMonitor-tree) {
  79. background-color: transparent;
  80. }
  81. </style>