Created
December 24, 2018 16:54
-
-
Save markusand/0d97366efe04e4aee101f62700cb30f2 to your computer and use it in GitHub Desktop.
Vue.js directive to trigger an event when a file is dropped on an element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
bind(el, bindings) { | |
el.dragEvents = ['dragenter', 'dragover', 'dragleave', 'drop']; | |
el.dragEvents.forEach(dragEvent => { | |
el.addEventListener(dragEvent, (event) => { | |
if (!el.classList.contains(dragEvent)) { | |
el.classList.remove(...el.dragEvents); | |
el.classList.add(dragEvent); | |
} | |
event.preventDefault(); | |
event.stopPropagation(); | |
}, false); | |
}); | |
el.addEventListener('drop', (event) => { | |
const file = event.dataTransfer.items | |
? event.dataTransfer.items[0].getAsFile() | |
: event.dataTransfer.files[0]; | |
const fakeFileEvent = { target: { files: [file] } }; | |
bindings.value(fakeFileEvent); | |
}, false); | |
}, | |
unbind(el) { | |
el.dragEvents.forEach(dragEvent => { | |
el.removeEventListener(dragEvent); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment