When building complex UIs with drag-and-drop functionality and nesting draggable components, this is a common use case. This guide will show you how to use Vue Draggable within another and get the parent DOM element.
How to Nest Vue Draggable Components
Vue Draggable (based on Sortable.js) allows nesting with independent lists. Here’s an example:
<template> <draggable v-model="sections" group="sections"> <template #item="{ element }">
<div class="section">
<draggable v-model="element.items" group="items">
<template #item="{ element }">
<div class="item">{{ element.name }}</div>
</template>
</draggable>
</div>
</template>
</draggable>
</template>
In this structure:
- sections is an array of section objects.
- Each section has its own items list.
- Both draggable elements operate in their own scope.
How to Get the Parent Element During Drag
You can get the parent element using the @start, @change, or @end event hooks provided by Vue Draggable.
<draggable v-model="items"
@start="onStart">
</draggable>
<script>
methods: {
onStart(event) {
const draggedEl = event.item; // dragged element
const parentEl = draggedEl.closest('.section'); // parent container
console.log('Parent Element:', parentEl);
}
}
</script>
Notes
- Use closest() for more flexible DOM traversal.
- Make sure parent containers have meaningful class names like .section or .wrapper.
Also Read: Why Enterprises are Choosing Vue.js for their Large-Scale Projects?
Tips
- Give parent containers unique class names for easy targeting.
- Use closest() instead of chaining parentElement calls.
- Don’t manipulate the DOM directly in deeply nested components unless necessary.
- Keep inner and outer list logic separate.
Conclusion
Nesting Vue Draggable is powerful for layered UIs. Accessing the parent element during drag events is straightforward using DOM traversal with event.item.
Related Resources