Skip to content

Instantly share code, notes, and snippets.

@nathanbarrett
Last active December 1, 2018 14:40
Show Gist options
  • Save nathanbarrett/58b511b20b445eab89e84f18da6b8b34 to your computer and use it in GitHub Desktop.
Save nathanbarrett/58b511b20b445eab89e84f18da6b8b34 to your computer and use it in GitHub Desktop.
A Vue component wrapper for dropzone.js that emits all events
<template>
<div :id="id" class="uploader dropzone"></div>
</template>
<script>
import Dropzone from 'dropzone';
Dropzone.autoDiscover = false;
export default {
props: ['options'],
data() {
return {
id: 'dropzone',
}
},
beforeMount() {
this.id = 'dropzone' + this._uid;
},
mounted() {
const params = {
...(this.options.params ? this.options.params : {}),
...{_token: window.csrf_token}
};
const options = {
...(this.options),
...{ params }
};
const dropzone = new Dropzone('div#' + this.id, options);
const actionEvents = [
'drop', 'dragstart', 'dragend', 'dragenter', 'dragover', 'dragleave'
];
actionEvents.forEach(actionEvent => {
dropzone.on(actionEvent, event => {
this.$emit(actionEvent, event, dropzone);
});
});
const fileEvents = [
'addedfile', 'removedfile', 'thumbnail', 'processing', 'uploadprogress', 'sending',
'complete', 'canceled', 'maxfilesreached', 'maxfilesexceeded',
];
fileEvents.forEach(fileEvent => {
dropzone.on(fileEvent, file => {
this.$emit(fileEvent, file, dropzone);
});
});
if(options.uploadMultiple !== false) {
const multipleFileEvents = [
'processingmultiple', 'sendingmultiple', 'successmultiple', 'completemultiple', 'canceledmultiple',
];
multipleFileEvents.forEach(multipleFileEvent => {
dropzone.on(multipleFileEvent, files => {
this.$emit(multipleFileEvent, files, dropzone);
});
});
}
const noParameterEvents = ['reset', 'queuecomplete'];
noParameterEvents.forEach(noParameterEvent => {
dropzone.on(noParameterEvent, () => {
this.$emit(noParameterEvent, dropzone);
});
});
dropzone.on('totaluploadprogress', (progress, totalBytes, totalBytesSent) => {
this.$emit('totaluploadprogress', progress, totalBytes, totalBytesSent, dropzone);
});
dropzone.on('success', (file, response) => {
this.$emit('success', file, response, dropzone);
});
dropzone.on('error', (file, errorMessage, response) => {
this.$emit('error', file, errorMessage, response, dropzone);
});
},
beforeDestroy() {
dropzone.destroy();
}
}
</script>
<style>
.uploader {
height: 250px;
border: 1px dashed #4596EC;
border-radius: 2px;
padding: 0;
overflow-y: hidden;
}
.uploader > .dz-message {
margin: 0;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment