delete content of file in vue 3

I have a Vue 3 component that looks like this:

<template>
    <input type="file" :class="inputClass" accept=".pdf" @input="onFileSelect" ref="fileInput">
</template>

<script>
import {ref} from "vue";

export default {
    name: "FileInput",
    props: {
        inputClass: String
    },
    setup(props, {emit}) {
        const fileInput = ref(null)

        const onFileSelect = () => {
            const input = fileInput.value;
            const files = input.files;
            if(files && files[0]) {
                const reader = new FileReader;

                reader.onload = e => {
                    emit('input', e.target.result);
                }

                reader.readAsDataURL(files[0]);
            }
        }

        return {fileInput, onFileSelect}
    }
}
</script>

and in the component where I use it:

<file-input input-class="form-control form-control-sm" v-model="document.doc_file" @input="getBase64File"/>

setup() {
 const getBase64File = (file) => {
   document.value.doc_file = file
 }

const document = ref({
  // ... other fields
  doc_file: null,            
})

 const resetDocumentModel = () => {
   for(let field in document.value) {
     document.value[field] = null
   }
 }
}

After submitting the form, the input file field still shows the filename and does not allow uploading the same file again.

How can I clear the input filename?

Answer №1

The solution to the issue turned out to be surprisingly straightforward.

To address the problem with the file input, an additional property called 'fileModel' was included in the code (alternatively, the provide - inject method can also be used):

props: ['inputClass', 'fileModel']

Subsequently, a watch was implemented to monitor any changes in the model's value and clear the input when it becomes null (reset):

const {fileModel} = toRefs(props)
watch(fileModel, (value) => {
    if(value === null) {
        fileInput.value.value = ''
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in identifying child element using class name

I need help accessing the element with the class "hs-input" within this structure: <div class = "hbspt-form".......> <form ....class="hs-form stacked"> <div class = "hs_firstname field hs-form-field"...> <div class = ...

Discover results while inputting in the search box

Can anyone assist me? I'm looking to enhance my current code by adding a search functionality to the ul list. I want users to be able to type in a search term and have the matches automatically highlighted as they type, similar to a "find-as-you-type ...

Managing input jQuery with special characters such as 'ä', 'ö', 'ü' poses a unique challenge

Hey there, I'm running into a bit of trouble with my code and I can't figure out why it's not working. Here's a brief overview: I created my own auto-suggest feature similar to jQuery UI autosuggest. Unfortunately, I'm unable t ...

Can you explain the meaning of `<%= something %>` to me?

I've been working on a javascript project and I'm curious about the purpose of surrounding a variable with this syntax? <%= variable %> I attempted to research it myself but didn't come across any helpful information, so my apologies ...

You can click on the link within the Leaflet Popup to trigger JavaScript functionality

My leaflet map is functioning with GeoJSON polygons and popups attached to each one. These popups display information about the polygon. I want a link inside the popup that, when clicked, triggers a JavaScript function to retrieve and display smaller polyg ...

Troubleshooting: Issue with Displaying $Http JSON Response in AngularJS View

Struggling to retrieve JSON data from an API and display it in a view using AngularJS. Although I am able to fetch the data correctly, I am facing difficulties in showing it in the view. Whenever I try to access the object's data, I constantly receive ...

Revamp the Twitter button parameters or alter its settings

I'm working on a web page that includes a Twitter button. Before the button, there is an input field and a form where users can easily add relevant hashtags for the page. The goal is to take the text from the input field and populate it in the Twitter ...

What is causing this code to malfunction in AngularJS version 1.2?

Check out this code snippet I wrote using Angular 1.2: http://jsfiddle.net/VmkQy/1/ <div ng-app="app"> Title is: <span my-directive data-title="Test title">{{ title }}</span> </div> angular.module('app', []) .dir ...

Jest tests are failing because React is not defined

I am attempting to implement unit tests using Jest and React Testing Library in my code. However, I have encountered an issue where the tests are failing due to the React variable being undefined. Below is my configuration: const { pathsToModuleNameMapper ...

Jersey/Jaxb is providing a result of strings rather than numbers

This is the structure that my jersey service returns: @XmlRootElement(name="chart-data") public class ChartDataDto { private List<Series> series = new ArrayList<>(); public ChartDataDto() { } public void putSeries(St ...

Dynamic Binding of Checkboxes in Vuex

I am encountering a problem with binding checkboxes using Vuex. Even though I am using v-model with a variable that has a getter and setter to set or get the value in the store, I keep getting incorrect data in the store. The issue arises when I click on a ...

Executing a file function from another within a module function in ReactJS

I need to utilize the functions that are defined in the apiGet.js file: export let apiGet = () => { return 'File One'; } These functions are being called in another module called brand.js. Here is the code snippet: require("../action ...

Disable object rotation when hovering the mouse over it in three.js

I've created a function to prevent the rotation of a three.js object when the mouse hovers over it. function onDocumentMouseUp( event ) { event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = - ( event.clientY / w ...

Is there a way to deactivate the toggle button in my code?

<label class="switch switch-yes-no" id="disable_'+id+'" style="margin: 0;font-weight: bold;"> <input class="switch-input" type="checkbox" id="disable_'+id+'" /> <span class="switch-label" data-on="Enabled" data-off="Disab ...

Tips for executing mocha tests using a reporter

Whenever I execute the command npm test, it displays this output: mocha ./tests/ --recursive --reporter mocha-junit-reporter All the tests are executed successfully. However, when I attempt to run mocha with ./tests/flickr/mytest --reporter junit-report ...

Adjusting the size of images in a Bootstrap lightbox gallery

I am currently working on a website for an artist, making the galleries a key aspect. The website is built using Bootstrap, with the Lightbox for Bootstrap plugin being used for the galleries. Everything seems to be working well in terms of adjusting the i ...

Enhancing UI Design with Styled-Components and Material Components using Media Queries

Struggling to grasp media queries with MUI and styled components. Take a look at the following syntax using styled-components: Syntax 1: const Video = styled.video` width: 860px; @media ${device.mobileSM} { width: 90%; } `; Additionally, there ...

Response text from AJAX in PHP

I am working on an AJAX sign up form and I would like to incorporate a gear wheel animation similar to this When the server successfully signs up a user, I want a specific bar to change to green. To achieve this, I have echoed the names of the functions I ...

How to set the value of an `<input type="date"` in jQuery

Having trouble figuring out why this code isn't functioning properly. The input field I'm using is a simple 'input type="date"' setup like this.... <input type="date" name="Date"/> I am attempting to have the value automatically ...

Retrieving text data from the JSON response received from the Aeris API

I am attempting to showcase the word "General" text on the HTML page using data from the API found under details.risk.type. The JSON Response Is As Follows... { "success": true, "error": null, "response": [ ...