siteTree.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <template>
  2. <div>
  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.selectable" icon="material-symbols:circle" />
  14. </template>
  15. </Tree>
  16. <p v-else>暂无数据</p>
  17. </div>
  18. </template>
  19. <script setup lang="ts">
  20. import { ref, watch } from 'vue';
  21. import { Tree } from 'ant-design-vue';
  22. import { MonitorSiteTreeNode } from '@/api/sys/model/monitorModel';
  23. import { TreeNode } from '../types/siteTree';
  24. import Icon from '@/components/Icon/Icon.vue';
  25. // props & emits
  26. const props = defineProps<{ treeData?: MonitorSiteTreeNode }>();
  27. const emit = defineEmits<{ select: [value: MonitorSiteTreeNode] }>();
  28. const processedTreeData = ref<TreeNode[]>([]);
  29. const expandedKeys = ref<string[]>([]);
  30. // 递归处理树节点并格式化为需要的格式,将父节点记录到指定数组中
  31. function walk(node: MonitorSiteTreeNode, parentNodeKeys: string[]): TreeNode {
  32. // 在这里赋值
  33. const res: TreeNode = {
  34. title: node.label,
  35. key: node.id,
  36. selectable: !!node.x,
  37. raw: node,
  38. children: [],
  39. };
  40. if (node.children) {
  41. // 记录所有的父节点id
  42. parentNodeKeys.push(node.id);
  43. node.children.forEach((child) => {
  44. res.children.push(walk(child, parentNodeKeys));
  45. });
  46. }
  47. return res;
  48. }
  49. function selectHandler(_, { selectedNodes }) {
  50. if (selectedNodes.length) {
  51. emit('select', selectedNodes[0]?.raw);
  52. }
  53. }
  54. // 更新逻辑在这里
  55. watch(
  56. () => props.treeData,
  57. (v) => {
  58. if (!v) return;
  59. expandedKeys.value = [];
  60. processedTreeData.value = [walk(v, expandedKeys.value)];
  61. },
  62. {
  63. immediate: true,
  64. },
  65. );
  66. defineExpose({
  67. processedTreeData,
  68. expandedKeys,
  69. });
  70. </script>