1

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:

<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.

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Using .value to get the value of the reactive variable solved my problem, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.