If you’re using the vuedraggable library for drag-and-drop functionality within Vue.js, and you want to access the parent element of a draggable item, you can achieve this by handling the change event emitted by the vuedraggable component. The change event provides information about the dragged item and its new position, including its old and new parent elements.
Here’s an example of how you can accomplish this:
<template> <div> <h2>Parent Container</h2> <draggable v-model="list" @change="handleDragChange"> <div v-for="(item, index) in list" :key="index"> <!-- Display draggable items here --> <div>{{ item }}</div> </div> </draggable> </div> </template> <script> import draggable from 'vuedraggable'; export default { components: { draggable }, data() { return { list: ['Item 1', 'Item 2', 'Item 3'] }; }, methods: { handleDragChange(event) { // Access the dragged item const draggedItem = event.moved.element; // Access the old parent element const oldParentElement = event.moved.oldIndex > -1 ? event.moved.oldContainer : null; // Access the new parent element const newParentElement = event.moved.newIndex > -1 ? event.moved.newContainer : null; console.log('Dragged Item:', draggedItem); console.log('Old Parent:', oldParentElement); console.log('New Parent:', newParentElement); } } }; </script>
In this example:
This way, you can access both the dragged item and its old and new parent elements when using the vuedraggable library in Vue.js.