12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <template>
- <div>
- <Tree
- v-if="processedTreeData.length"
- :tree-data="processedTreeData"
- :default-expand-all="true"
- :virtual="false"
- :show-icon="true"
- @select="selectHandler"
- >
- <template #icon="scope">
- <Icon v-if="scope.selected" icon="material-symbols:circle" color="green" />
- <Icon v-else-if="scope.selectable" icon="material-symbols:circle" />
- </template>
- </Tree>
- <p v-else>暂无数据</p>
- </div>
- </template>
- <script setup lang="ts">
- import { ref, watch } from 'vue';
- import { Tree } from 'ant-design-vue';
- import { MonitorSiteTreeNode } from '@/api/sys/model/monitorModel';
- import { TreeNode } from '../types/siteTree';
- import Icon from '@/components/Icon/Icon.vue';
- // props & emits
- const props = defineProps<{ treeData?: MonitorSiteTreeNode }>();
- const emit = defineEmits<{ select: [value: MonitorSiteTreeNode] }>();
- const processedTreeData = ref<TreeNode[]>([]);
- const expandedKeys = ref<string[]>([]);
- // 递归处理树节点并格式化为需要的格式,将父节点记录到指定数组中
- function walk(node: MonitorSiteTreeNode, parentNodeKeys: string[]): TreeNode {
- // 在这里赋值
- const res: TreeNode = {
- title: node.label,
- key: node.id,
- selectable: !!node.x,
- raw: node,
- children: [],
- };
- if (node.children) {
- // 记录所有的父节点id
- parentNodeKeys.push(node.id);
- node.children.forEach((child) => {
- res.children.push(walk(child, parentNodeKeys));
- });
- }
- return res;
- }
- function selectHandler(_, { selectedNodes }) {
- if (selectedNodes.length) {
- emit('select', selectedNodes[0]?.raw);
- }
- }
- // 更新逻辑在这里
- watch(
- () => props.treeData,
- (v) => {
- if (!v) return;
- expandedKeys.value = [];
- processedTreeData.value = [walk(v, expandedKeys.value)];
- },
- {
- immediate: true,
- },
- );
- defineExpose({
- processedTreeData,
- expandedKeys,
- });
- </script>
|