Skip to content

Instantly share code, notes, and snippets.

@alonextou
Forked from dohomi/app.vue
Created September 16, 2018 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alonextou/1b620f22af8ef8dd9a2aa86a7dfe1831 to your computer and use it in GitHub Desktop.
Save alonextou/1b620f22af8ef8dd9a2aa86a7dfe1831 to your computer and use it in GitHub Desktop.
Small file input element based on vuetify
<template>
<file-input v-model="filename" @formData="formData">
<v-btn @click.native="uploadFiles">
</template>
<script>
import fileInput from './file-input.vue'
export default{
components:{fileInput}
methods:{
uploadFiles(){
// your custom upload method
const form = this.formData
console.log(form)
}
}
}
</script>
<template>
<div>
<v-text-field prepend-icon="attach_file" single-line
v-model="filename" :label="$t(label).toUpperCase()" :required="required"
@click.native="onFocus"
:disabled="disabled" ref="fileTextField"></v-text-field>
<input type="file" :accept="accept" :multiple="multiple" :disabled="disabled"
ref="fileInput" @change="onFileChange">
</div>
</template>
<script>
export default {
props: {
value: {
type: [Array, String]
},
accept: {
type: String,
default: '*'
},
label: {
type: String,
default: 'choose_file'
},
required: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
multiple: {
type: Boolean,
default: false
}
},
data () {
return {
filename: ''
}
},
watch: {
value (v) {
this.filename = v
}
},
mounted () {
this.filename = this.value
},
methods: {
getFormData (files) {
const forms = []
for (const file of files) {
const form = new FormData()
form.append('data', file, file.name)
forms.push(form)
}
return forms
},
onFocus () {
if (!this.disabled) {
this.$refs.fileInput.click()
}
},
onFileChange ($event) {
const files = $event.target.files || $event.dataTransfer.files
const form = this.getFormData(files)
if (files) {
if (files.length > 0) {
this.filename = [...files].map(file => file.name).join(', ')
} else {
this.filename = null
}
} else {
this.filename = $event.target.value.split('\\').pop()
}
this.$emit('input', this.filename)
this.$emit('formData', form)
}
}
}
</script>
<style scoped>
input[type=file] {
position: absolute;
left: -99999px;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment