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:

  • We have a parent container with draggable items rendered inside the vuedraggable component.
  • We’re listening for the change event emitted by the vuedraggable component and calling the handleDragChange method when a drag-and-drop operation occurs.
  • Inside the handleDragChange method, we access the dragged item (event.moved.element), the old parent element (event.moved.oldContainer), and the new parent element (event.moved.newContainer).
  • We then log these values to the console for demonstration purposes, but you can perform any necessary actions based on this information.

This way, you can access both the dragged item and its old and new parent elements when using the vuedraggable library in Vue.js.

Support On Demand!

Vue