Skip to content

Instantly share code, notes, and snippets.

@Rockbass
Forked from dohomi/app.vue
Created January 10, 2018 10:30
Show Gist options
  • Save Rockbass/f7be567494da4c970027f9238729ccb2 to your computer and use it in GitHub Desktop.
Save Rockbass/f7be567494da4c970027f9238729ccb2 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