A Simple vue3 project for rendering items in a tree.
<template>
<vue3-tree-vue :items="items"
:isCheckable="false" //Set to true if you want to get checkable items
:hideGuideLines="false"
@onCheck="onItemChecked"
@dropValidator="onBeforeItemDropped"
@onSelect="onItemSelected"
@onExpand="onItemExpanded"
>
<!-- Applying some simple styling to tree-items -->
<template v-slot:item-prepend-icon="treeViewItem" >
<img src="./assets/folder.svg"
alt="folder"
v-if="treeViewItem.type === 'folder'"
height="20" width="20" />
</template>
</vue3-tree-vue>
</template>
import 'vue3-tree-vue/dist/style.css'; // remember to add this in your component or maint.[ts/js]
setup() {
const onItemChecked = (checkedItems: TreeViewItem[]) => console.log(checkedItems);
const onItemSelected = (item: TreeViewItem) => console.log(item);
// How to handle drag and drop logic
const onBeforeItemDropped = (droppedItem: TreeViewItem, destinationNode: TreeViewItem | undefined) => {
// destinationNode == undefined means dropping at the root of the tree.
// Here you can specify any kind of drop validation you will like.
// this function should return true if the drop operation is valid.
return new Promise((resolve, _) => {
resolve(droppedItem !== destinationNode) // Replace this logic with your logic.
});
}
const onItemExpanded = (expandedItem: TreeViewItem) => {
//to use this feature properly you need to set lazyLoad property as true
//fetch data
const lazyLoadedItems = fetchFromApi(...);
expandedItem.children.push(...lazyLoadedItems)
}
const items = ref<TreeViewItem[]>([]); // define your tree items here.
return {
onItemChecked,
onItemSelected,
onBeforeItemDropped,
onItemExpanded,
items
}
}
export interface TreeViewItem {
name: string;
id?: string | number;
children?: TreeViewItem[];
checked?: boolean;
selected?: boolean;
expanded?: boolean;
disableDragAndDrop?: boolean; // Disable drag and drop for a specific node.
disabled?: boolean;// When disabled, an item can neither be selected nor checked
styles?: string[]; // Add the .css styles for a given item
meta?: any;// provides meta-data of any type per node.
}