DEV Community

Schleidens.dev
Schleidens.dev

Posted on

How to get file* input value in Vue.js (Vue3)

In Vue.js, accessing the value of an input element is typically straightforward thanks to the v-model directive. However, when it comes to file input fields, the v-model directive doesn't work directly. This can be a bit puzzling for developers who want to retrieve the selected file from a file input field in a Vue.js 3 application.

In this article, we will explore an approach to tackle this challenge and find a solution for getting the file input value in Vue.js 3. By the end, you will have a clear understanding of how to extract the selected file from a file input field and use it within your Vue.js application.

Composition API, script setup

Here my HTML input file.
<input class="form-control" type="file" id="formFile">

Now let's go directly in the component's script section.
Create a reactive value reference for our input using ref
const myFileInputValue = ref(null);
Don't forget to import ref on top of our script section.

Create a function to get the input value.

const getFileInputValue = (event) => {
    //get the file input value
    const file = event.target.files;
    //assign it to our reactive reference value 
    myFileInputValue.value = file[0] 
}
Enter fullscreen mode Exit fullscreen mode

file[0] is used to assign the first selected file to myFileInputValue.

Great !! now we have to call this function every time our input value change.
We can use the v-on vue.js directive also know as @ in the component template with the change event.
change is the equivalent of the onchange native event handler
v-on:change="getFileInputValue" or @change="getFileInputValue"

Our input code look like this now.

<input v-on:change="getFileInputValue" class="form-control" type="file" id="formFile">

or

<input @change="getFileInputValue" class="form-control" type="file" id="formFile">
Enter fullscreen mode Exit fullscreen mode

Now that you have learned how to retrieve file input values in Vue.js 3, you can confidently handle file inputs in your own projects. Take advantage of the versatile file input capabilities offered by Vue.js 3 and explore the possibilities. Enjoy coding and happy file handling!

Top comments (0)