Blog>
Snippets

Drag-and-Drop Directive

Develop a custom directive that enables drag-and-drop functionality on the bound element, with support for transfer data.
Vue.directive('draggable', {
  bind: function(el, binding) {
    el.draggable = true;

    el.addEventListener('dragstart', function(e) {
      e.dataTransfer.setData('text', binding.value);
      el.classList.add('dragging'); // Add a class to style while dragging
    });

    el.addEventListener('dragend', function(e) {
      el.classList.remove('dragging'); // Remove the dragging class
    });
  }
});
Creates a custom Vue directive 'draggable' that enables any element with this directive to be draggable. When the drag starts, it will add a class 'dragging' to the element and use the binding value as the data to be transferred. When the drag ends, it removes the 'dragging' class.
Vue.directive('droppable', {
  bind: function(el, binding) {
    el.addEventListener('dragover', function(e) {
      e.preventDefault(); // Necessary to allow a drop
      el.classList.add('drag-over'); // Add class to style on drag over
    });

    el.addEventListener('dragleave', function(e) {
      el.classList.remove('drag-over'); // Remove the drag over class
    });

    el.addEventListener('drop', function(e) {
      const data = e.dataTransfer.getData('text');
      binding.value(data, e); // Call the bound function with the transferred data
      el.classList.remove('drag-over'); // Clean up drag over class
    });
  }
});
Creates a custom Vue directive 'droppable' that allows an element to accept drop actions. It manages the visual feedback during drag-over and calls the function provided via the binding when a drop occurs, passing the transferred data as an argument.