2

I have this vue component in vue 3

<template>
    <input type="file" :class="inputClass" accept=".pdf" @input="onFileSelect" ref="fileInput">
</template>

<script>
import {ref} from "vue";

export default {
    name: "FileInput",
    props: {
        inputClass: String
    },
    setup(props, {emit}) {
        const fileInput = ref(null)

        const onFileSelect = () => {
            const input = fileInput.value;
            const files = input.files;
            if(files && files[0]) {
                const reader = new FileReader;

                reader.onload = e => {
                    emit('input', e.target.result);
                }

                reader.readAsDataURL(files[0]);
            }
        }

        return {fileInput, onFileSelect}
    }
}
</script>

and in the component where I use it:

<file-input input-class="form-control form-control-sm" v-model="document.doc_file" @input="getBase64File"/>

setup() {
 const getBase64File = (file) => {
   document.value.doc_file = file
 }

const document = ref({
  // ... other fields
  doc_file: null,            
})

 const resetDocumentModel = () => {
   for(let field in document.value) {
     document.value[field] = null
   }
 }
}

after submit the form in the input file filed still remains the filename and if I try to upload the same file again it won't take it.

How to clear the input filename ?

1 Answer 1

4

The solution was very simple :)

In the file input I added another prop fileModel (or you can use provide - inject):

props: ['inputClass', 'fileModel']

Then watch for changes when the model value becomes null (reset) then clear the input

const {fileModel} = toRefs(props)
watch(fileModel, (value) => {
    if(value === null) {
        fileInput.value.value = ''
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.