DevExtreme v24.1 is now available.

Explore our newest features/capabilities and share your thoughts with us.

Your search did not match any results.

Vue Tree View - Drag & Drop for Hierarchical Data Structure

This sample app demonstrates node drag and drop operations within DevExtreme TreeView when using a hierarchical data structure. You can reorder nodes within a single tree view or drag and drop nodes between two separate tree views.

Backend API
<template> <div class="form"> <div class="drive-panel"> <div class="drive-header dx-treeview-item" ><div class="dx-treeview-item-content" ><i class="dx-icon dx-icon-activefolder"/><span>Drive C:</span></div></div> <DxSortable filter=".dx-treeview-item" group="shared" data="driveC" :allow-drop-inside-item="true" :allow-reordering="true" @drag-change="onDragChange" @drag-end="onDragEnd" > <DxTreeView id="treeviewDriveC" data-structure="tree" :expand-nodes-recursive="false" ref="treeViewDriveCRef" :items="itemsDriveC" :width="250" :height="380" display-expr="name" /> </DxSortable> </div> <div class="drive-panel"> <div class="drive-header dx-treeview-item" ><div class="dx-treeview-item-content" ><i class="dx-icon dx-icon-activefolder"/><span>Drive D:</span></div></div> <DxSortable filter=".dx-treeview-item" group="shared" data="driveD" :allow-drop-inside-item="true" :allow-reordering="true" @drag-change="onDragChange" @drag-end="onDragEnd" > <DxTreeView id="treeviewDriveD" data-structure="tree" :expand-nodes-recursive="false" ref="treeViewDriveDRef" :items="itemsDriveD" :width="250" :height="380" display-expr="name" /> </DxSortable> </div> </div> </template> <script setup lang="ts"> import { nextTick, ref } from 'vue'; import DxTreeView from 'devextreme-vue/tree-view'; import DxSortable from 'devextreme-vue/sortable'; import service from './data.ts'; const itemsDriveC = ref(service.getItemsDriveC()); const itemsDriveD = ref(service.getItemsDriveD()); const treeViewDriveCRef = ref(); const treeViewDriveDRef = ref(); function onDragChange(e) { if (e.fromComponent === e.toComponent) { const fromNode = findNode(getTreeView(e.fromData), e.fromIndex); const toNode = findNode(getTreeView(e.toData), calculateToIndex(e)); if (toNode !== null && isChildNode(fromNode, toNode)) { e.cancel = true; } } } function onDragEnd(e) { if (e.fromComponent === e.toComponent && e.fromIndex === e.toIndex) { return; } const fromTreeView = getTreeView(e.fromData); const toTreeView = getTreeView(e.toData); const fromNode = findNode(fromTreeView, e.fromIndex); const toNode = findNode(toTreeView, calculateToIndex(e)); if (e.dropInsideItem && toNode !== null && !toNode.itemData.isDirectory) { return; } const fromTopVisibleNode = getTopVisibleNode(e.fromComponent); const toTopVisibleNode = getTopVisibleNode(e.toComponent); const fromItems = getItems(e.fromData); const toItems = getItems(e.toData); moveNode(fromNode, toNode, fromItems, toItems, e.dropInsideItem); itemsDriveC.value = [].concat(itemsDriveC.value); itemsDriveD.value = [].concat(itemsDriveD.value); nextTick().then(() => { fromTreeView.scrollToItem(fromTopVisibleNode); toTreeView.scrollToItem(toTopVisibleNode); }); } function getTreeView(driveName) { return driveName === 'driveC' ? treeViewDriveCRef.value.instance : treeViewDriveDRef.value.instance; } function getItems(driveName) { return driveName === 'driveC' ? itemsDriveC.value : itemsDriveD.value; } function calculateToIndex(e) { if (e.fromComponent !== e.toComponent || e.dropInsideItem) { return e.toIndex; } return e.fromIndex >= e.toIndex ? e.toIndex : e.toIndex + 1; } function findNode(treeView, index) { const nodeElement = treeView.element().querySelectorAll('.dx-treeview-node')[index]; if (nodeElement) { return findNodeById(treeView.getNodes(), nodeElement.getAttribute('data-item-id')); } return null; } function findNodeById(nodes, id) { for (let i = 0; i < nodes.length; i += 1) { if (nodes[i].itemData.id === id) { return nodes[i]; } if (nodes[i].children) { const node = findNodeById(nodes[i].children, id); if (node != null) { return node; } } } return null; } function moveNode(fromNode, toNode, fromItems, toItems, isDropInsideItem) { const fromNodeContainingArray = getNodeContainingArray(fromNode, fromItems); const fromIndex = fromNodeContainingArray .findIndex((item) => item.id === fromNode.itemData.id); fromNodeContainingArray.splice(fromIndex, 1); if (isDropInsideItem) { toNode.itemData.items.splice(toNode.itemData.items.length, 0, fromNode.itemData); } else { const toNodeContainingArray = getNodeContainingArray(toNode, toItems); const toIndex = toNode === null ? toNodeContainingArray.length : toNodeContainingArray.findIndex((item) => item.id === toNode.itemData.id); toNodeContainingArray.splice(toIndex, 0, fromNode.itemData); } } function getNodeContainingArray(node, rootArray) { return node === null || node.parent === null ? rootArray : node.parent.itemData.items; } function isChildNode(parentNode, childNode) { let { parent } = childNode; while (parent !== null) { if (parent.itemData.id === parentNode.itemData.id) { return true; } parent = parent.parent; } return false; } function getTopVisibleNode(component) { const treeViewElement = component.element(); const treeViewTopPosition = treeViewElement.getBoundingClientRect().top; const nodes = treeViewElement.querySelectorAll('.dx-treeview-node'); for (let i = 0; i < nodes.length; i += 1) { const nodeTopPosition = nodes[i].getBoundingClientRect().top; if (nodeTopPosition >= treeViewTopPosition) { return nodes[i]; } } return null; } </script> <style scoped> .form { display: flex; } .form > div { display: inline-block; vertical-align: top; } .dx-treeview-item { box-sizing: border-box; } .drive-header { min-height: auto; padding: 0; cursor: default; margin-bottom: 10px; } .drive-panel { padding: 20px 30px; font-size: 115%; font-weight: bold; border-right: 1px solid rgba(165, 165, 165, 0.4); height: 100%; } .drive-panel:last-of-type { border-right: none; } </style>
window.exports = window.exports || {}; window.config = { transpiler: 'plugin-babel', meta: { '*.vue': { loader: 'vue-loader', }, '*.ts': { loader: 'demo-ts-loader', }, '*.svg': { loader: 'svg-loader', }, 'devextreme/time_zone_utils.js': { 'esModule': true, }, 'devextreme/localization.js': { 'esModule': true, }, 'devextreme/viz/palette.js': { 'esModule': true, }, }, paths: { 'root:': '../../../../', 'npm:': 'https://unpkg.com/', }, map: { 'vue': 'npm:vue@3.2.47/dist/vue.esm-browser.js', 'vue-loader': 'npm:dx-systemjs-vue-browser@1.1.1/index.js', 'demo-ts-loader': 'root:utils/demo-ts-loader.js', 'svg-loader': 'root:utils/svg-loader.js', 'mitt': 'npm:mitt/dist/mitt.umd.js', 'rrule': 'npm:rrule@2.6.4/dist/es5/rrule.js', 'luxon': 'npm:luxon@1.28.1/build/global/luxon.min.js', 'es6-object-assign': 'npm:es6-object-assign@1.1.0', 'devextreme': 'npm:devextreme@24.1.7/cjs', 'devextreme-vue': 'npm:devextreme-vue@24.1.7/cjs', 'jszip': 'npm:jszip@3.10.1/dist/jszip.min.js', 'devextreme-quill': 'npm:devextreme-quill@1.7.1/dist/dx-quill.min.js', 'devexpress-diagram': 'npm:devexpress-diagram@2.2.13/dist/dx-diagram.js', 'devexpress-gantt': 'npm:devexpress-gantt@4.1.56/dist/dx-gantt.js', '@devextreme/runtime': 'npm:@devextreme/runtime@3.0.13', 'inferno': 'npm:inferno@7.4.11/dist/inferno.min.js', 'inferno-compat': 'npm:inferno-compat/dist/inferno-compat.min.js', 'inferno-create-element': 'npm:inferno-create-element@7.4.11/dist/inferno-create-element.min.js', 'inferno-dom': 'npm:inferno-dom/dist/inferno-dom.min.js', 'inferno-hydrate': 'npm:inferno-hydrate@7.4.11/dist/inferno-hydrate.min.js', 'inferno-clone-vnode': 'npm:inferno-clone-vnode/dist/inferno-clone-vnode.min.js', 'inferno-create-class': 'npm:inferno-create-class/dist/inferno-create-class.min.js', 'inferno-extras': 'npm:inferno-extras/dist/inferno-extras.min.js', 'plugin-babel': 'npm:systemjs-plugin-babel@0.0.25/plugin-babel.js', 'systemjs-babel-build': 'npm:systemjs-plugin-babel@0.0.25/systemjs-babel-browser.js', // Prettier 'prettier/standalone': 'npm:prettier@2.8.8/standalone.js', 'prettier/parser-html': 'npm:prettier@2.8.8/parser-html.js', }, packages: { 'devextreme-vue': { main: 'index.js', }, 'devextreme': { defaultExtension: 'js', }, 'devextreme/events/utils': { main: 'index', }, 'devextreme/events': { main: 'index', }, 'es6-object-assign': { main: './index.js', defaultExtension: 'js', }, }, packageConfigPaths: [ 'npm:@devextreme/*/package.json', 'npm:@devextreme/runtime@3.0.13/inferno/package.json', ], babelOptions: { sourceMaps: false, stage0: true, }, }; System.config(window.config);
const itemsDriveD = []; const itemsDriveC = [{ id: '1', name: 'Documents', icon: 'activefolder', isDirectory: true, expanded: true, items: [{ id: '2', name: 'Projects', icon: 'activefolder', isDirectory: true, expanded: true, items: [{ id: '3', name: 'About.rtf', icon: 'file', isDirectory: false, }, { id: '4', name: 'Passwords.rtf', icon: 'file', isDirectory: false, }, ], }, { id: '5', name: 'About.xml', icon: 'file', isDirectory: false, }, { id: '6', name: 'Managers.rtf', icon: 'file', isDirectory: false, }, { id: '7', name: 'ToDo.txt', icon: 'file', isDirectory: false, }, ], }, { id: '8', name: 'Images', icon: 'activefolder', isDirectory: true, expanded: true, items: [{ id: '9', name: 'logo.png', icon: 'file', isDirectory: false, }, { id: '10', name: 'banner.gif', icon: 'file', isDirectory: false, }, ], }, { id: '11', name: 'System', isDirectory: true, icon: 'activefolder', expanded: true, items: [{ id: '12', name: 'Employees.txt', icon: 'file', isDirectory: false, }, { id: '13', name: 'PasswordList.txt', icon: 'file', isDirectory: false, }, ], }, { id: '14', name: 'Description.rtf', icon: 'file', isDirectory: false, }, { id: '15', name: 'Description.txt', icon: 'file', isDirectory: false, }]; export default { getItemsDriveC() { return itemsDriveC; }, getItemsDriveD() { return itemsDriveD; }, };
import { createApp } from 'vue'; import App from './App.vue'; createApp(App).mount('#app');
<!DOCTYPE html> <html lang="en"> <head> <title>DevExtreme Demo</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/24.1.7/css/dx.light.css" /> <script src="https://unpkg.com/typescript@4.9.5/lib/typescript.js"></script> <script type="module"> import * as vueCompilerSFC from "https://unpkg.com/@vue/compiler-sfc@3.4.16/dist/compiler-sfc.esm-browser.js"; window.vueCompilerSFC = vueCompilerSFC; </script> <script src="https://unpkg.com/core-js@2.6.12/client/shim.min.js"></script> <script src="https://unpkg.com/systemjs@0.21.3/dist/system.js"></script> <script type="text/javascript" src="config.js"></script> <script type="text/javascript"> System.import("./index.ts"); </script> </head> <body class="dx-viewport"> <div class="demo-container"> <div id="app"> </div> </div> </body> </html>

Use Sortable to implement the necessary drag and drop functionality within your web app. The following steps outline configuration requirements for our TreeView:

  1. Allow users to reorder nodes
    Wrap the TreeView in a Sortable and enable the Sortable's allowReordering property.

  2. Allow users to change node hierarchy
    Enable the allowDropInsideItem property so that users can drop one node onto another. This adds it as the target node's child. If this property is disabled, users can only drop nodes between other nodes.

  3. Allow users to drag only tree view nodes
    To specify tree view nodes as drag targets, set the filter property to a class selector. Since all tree view nodes use the dx-treeview-node class, you can use this class selector as needed.

  4. Prevent a node from being moved into its child node
    When a user moves a parent node into its own child node, it breaks the hierarchy. To prevent this outcome, implement the onDragChange function and traverse up the node tree. If the target is a child of the dragged node, cancel the ability to drop the node.

  5. Reorder nodes in code
    Implement the onDragEnd function. In this function, you must gather information about nodes being moved. With this information, you can reorder the nodes in the data source (see the moveNode function), and reassign the data source to the TreeView's items property.

  6. Specify tree view identifiers (for drag and drop between multiple tree views only)
    Identifiers help distinguish between multiple tree views. Save them in the Sortable's data property. The tree views below include the following identifiers: "driveC" and "driveD".

  7. Combine tree views into one drag and drop group (for drag and drop between multiple tree views only)
    Set the Sortable's group property to the same value for all tree views. This allows users to move nodes between the tree views.