const menuAddPopupIsOpen = ref<boolean>(false);
const menusData = ref<IData[]>([]);
const inquiryMenus = async () => {
try {
const res = await axios.get("/api/v1/menus");
menusData.value = res.data.body.data;
console.log(menusData.value);
} catch (error) {
console.error("MenuList.vue error / inquiryMenus error" + error);
}
};
class TreeNode {
data: IData;
label: string;
parent: TreeNode | null;
children: TreeNode[];
constructor(data: IData) {
this.data = data;
this.parent = null;
this.children = [];
this.label = data.menuName;
}
insertChild(node: TreeNode) {
this.children.push(node);
}
static isParentNode(parent: TreeNode, child: TreeNode): boolean {
return parent.data.menuId === child.data.parentId;
}
addTreeToParent(target: TreeNode): TreeNode | null {
if (TreeNode.isParentNode(this, target)) {
this.insertChild(target);
return this;
}
for (let i = 0; i < this.children.length; i++) {
const existParent: any = this.children[i].addTreeToParent(target);
if (existParent) {
return existParent;
}
}
return null;
}
}
let newTreeArrData = reactive<TreeNode[]>([]);
watch(
() => menusData.value,
(newVal) => {
console.log("newVal menus data: " + newVal);
apiToTree();
console.log("newTreeArrData: ", newTreeArrData);
treeToData();
console.log("treeToData: ", result.value);
},
{ deep: true }
);
function apiToTree() {
newTreeArrData = [];
for (let i = 0; i < menusData.value.length; i++) {
const data = menusData.value[i];
const currNode = new TreeNode(data);
if (!data.parentId) {
newTreeArrData.push(currNode);
console.info("currNode is top", currNode.data.menuId);
continue;
}
let added = false;
for (let i = 0; i < newTreeArrData.length; i++) {
const exist = newTreeArrData[i];
const parent = exist.addTreeToParent(currNode);
if (parent) break;
}
if (!added) {
console.log("not added any nodes", currNode.data);
}
}
console.log(newTreeArrData);
}
interface TreeData {
label: string;
children: TreeData[];
}
const toTreeData = (tree: TreeNode): TreeData => {
return {
label: tree.label,
children: tree.children.map((x) => toTreeData(x)).flat(),
};
};
let result = ref<TreeData[]>([]);
function treeToData() {
result.value = newTreeArrData.map(toTreeData);
}
const handleNodeClick = (data: IData) => {
console.log(data);
};
const defaultProps = {
children: "children",
label: "label",
};
const menuAddPopupOpen = () => {
menuAddPopupIsOpen.value = true;
};
onMounted(() => {
inquiryMenus();
});
</script>