Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to dynamically render an input value of type=file in Vue3?

I got an input field of type=’file’, what I am trying to achieve in my nuxt project is showing the filename that is uploaded, to the user. I know that by default input type=file is already showing the value but i made the input’s opacity 0 for styling purposes.

I have tried to write a function that finds the filename selected with the input. Then i assigned the file name to a reactive variable with ref() and returned that variable in that function. Then i put that reactive variable inside double curly braces to render it dynamically in the page and called the function everytime input value changes.

The function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script setup>

 const inputField = ref(null);
 var fileName = ref(null);

 function changeFileName(file) {
   if (file.files[0] != null) {
     return (fileName = file.files[0].name);
   } else return (fileName = "");
 }

</script>

Where I called it in the code:

<template>
 <div>

  <b>{{ fileName }}</b>

  <input
   type="file"
   ref="inputField"
   @change="changeFileName(inputField)"
  />

 </div>
</template>

So I expected to change the variable "fileName"’s value everytime users select a file from their computer and render the value dynamically to show which file is selected but it seems like curly braces ( {{}} ) is not catching the changed value because after selecting a file, fileName’s value is changing but the old value continues to be displayed on the page.

>Solution :

Try to bind the reactive property with input value using value and change event, and assign value to the ref property using .value field :

<script setup>
import { ref } from 'vue'

const fileName = ref("")
 function changeFileName(e) {
   console.log(e)
   if (e.target.files[0] != null) {
      fileName.value = e.target.files[0].name;
   } else  fileName.value = "";
 }
</script>

<template>
  <h1>{{ fileName }}</h1>
  <input  type="file" :value="fileName" @change="changeFileName"/>
</template>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading