[英]clear input file in vue 3
I have this vue component in vue 3我在 vue 3 中有这个 vue 组件
<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?如何清除输入文件名?
The solution was very simple:)解决方案非常简单:)
In the file input I added another prop fileModel (or you can use provide - inject):在文件输入中,我添加了另一个道具 fileModel(或者您可以使用提供 - 注入):
props: ['inputClass', 'fileModel']
Then watch for changes when the model value becomes null (reset) then clear the input然后观察 model 值变为 null(复位)时的变化,然后清除输入
const {fileModel} = toRefs(props)
watch(fileModel, (value) => {
if(value === null) {
fileInput.value.value = ''
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.