DEV Community

Cover image for Vue 3 // v-model on custom component input type="file"
Salvador García
Salvador García

Posted on

Vue 3 // v-model on custom component input type="file"

Hi everyone. Let's get to the point. A few days ago I needed to use v-model in a component of my own that I needed to capture a file in an input of type file. After trying a bit, the solution was the following:

<template>

  <input type="file" @change="onChangeFile" name="file" />

</template>

<script>
  methods: {
    onChangeFile(event) {
      this.$emit('update:modelValue', event.target.files[0])
    }
</script>

//Your component made in Vue 3
<MyInputFileComponent v-model="file" />
Enter fullscreen mode Exit fullscreen mode

This is the easiest way to use it. If you need to capture many files you just have to go through the list of files found in the e.target.files

I share this information in case there is anyone out there looking for a solution for this scenario. Happy dev.

Discussion (2)

Collapse
furkanulutasx profile image
Furkan

Why did you "file" the v-model name?

Collapse
erefor profile image
Salvador García Author

It is just an example name. It could be: "userFile", "userPhoto", "salesRecord", etc...