How to Reset the File input Field in Vue js
In this lesson, we will see how to reset the file input field in Vue js.
When uploading files using Vue js we want to clear the file input field, so how can we do that?
Reset the file input field in Vue js
To do that first, we need to define a data property here I call it fileInputKey and I give it 0 as the value, next we give the file input field a key which is the property we defined, finally once the file is uploaded we increment the property by one and the file input field will be cleared.
<template> <div class="input-group my-3"> <input type="file" class="form-control" @change="handleInputFileChange" :key="data.fileInputKey" /> <button class="btn btn-sm btn-primary" @click="uploadImage" > Upload </button> </div></template>
<script setup> import { reactive } from "vue"
//define the data object const data = reactive({ image: null, fileInputKey: 0 })
//handle file input change const handleInputFileChange = (event) => { data.image = event.target.files[0]; }
//upload image function const uploadImage= async () => { console.log('image uploaded') //clear the file input field data.fileInputKey++ }</script>