What is the best way to set the input type file to null when deleting an image in Vue?

My form allows users to upload an image, and everything was functioning properly until I encountered an issue. When I remove an image and try to upload the same image again, the @change function is not triggered. I am unable to reset the file value to null.

I attempted changing this.$refs.fileInput.type when removing the image, setting the ref files to null, and even trying to set the value to null.

<template>
  <div>

    <v-layout>

      <v-container style="margin:0px">

        <v-form>
<v-badge right v-if="certificateImage" color="red" class="close-btn">
                     <span slot="badge" @click="removeImage">X</span>
                    <img :src="certificateImage" height="150px"  
    @click="onPickFile">
                   </v-badge>
                    <img v-if="!certificateImage" 
   src="https://imgplaceholder.com/640x360" height="150px"  @click="onPickFile">
                    <input type="file" style="display:none" 
ref="fileInput" id="fileInput" accept="image/*" @change="onFilePicked">

</v-form>
      </container>
</layout>
/div>

</template>
<script>
data(){
    return{
certificateImage:"",

}
},
methods:{
onPickFile(){
        this.$refs.fileInput.click()


      },
      onFilePicked(event){
console.log(this.$refs.fileInput.type,"sdfds");
        const files=event.target.files;
         let filename =files[0].name;
        if(filename.lastIndexOf('.')<=0){
          return alert('Please enter a valid image')

        }
        const fileReader=new FileReader();

        fileReader.addEventListener('load',()=>{
          this.certificateImage=fileReader.result;
          console.log(this.certificateImage,"image url");
        })
        fileReader.readAsDataURL(files[0])
        this.image=files[0]
            // Create a root reference

      },

}
 removeImage: function (e) {
        console.log('removed')
      this.certificateImage = '';
this.$refs.fileInput.type='text';
this.$refs.fileInput.type='file';
    },
</script>
<style scoped>

.image1{
  padding-top:5px;
  width:35px
}
.image2{
  width:80px;
}
.remove{
  width: 12px;
    border-radius: 50%;
    background: red;
    color:white;

}
input[type=file] {
  cursor: pointer;
  width: 159px;
  height: 34px;
  overflow: hidden;
}

input[type=file]:before {
  width: 158px;
  height: 32px;
  font-size: 16px;
  line-height: 32px;
  content: 'Select your file';
  display: inline-block;
  background: #808080;
  color:white;
  border: 1px solid #0000002e;
  padding: 0 10px;
  text-align: center;
  font-family: Helvetica, Arial, sans-serif;
}

input[type=file]::-webkit-file-upload-button {
  visibility: hidden;
}
.selectImage{
    color: #00000085;
    padding-left: 5px;
    float: left;
    padding-right: 10px;
    padding-top: 4px;
}
.selectIcon{
    color: #00000085;
    padding-left: 5px;
    float: left;
    padding-right: 10px;
    padding-top: 4px;
}
.close-btn:hover{
  cursor:pointer;
}
</style>

After attempting to reupload an image that was previously removed, I need the function to run upon changing the input type file.

Answer №1

Issue resolved as I was referencing the wrong source, but now it is functioning correctly.

Answer №2

Give this a shot:

...
 functionality: {
   clearImage () {
      document.querySelector('#fileInput').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

Customize the appearance of each element in ng-repeat individually

In my code, I have implemented an ng-repeat. Each alternate div inside the ng-repeat is supposed to have a different border-color, which is achieved by using the following structure: <div ng-repeat="channel in channelList"> <div ng-style="get ...

The query parameter is not defined in the router of my Next.js app API

I'm currently working on building an API endpoint for making DELETE requests to remove albums from a user's document in the MongoDB Atlas database. Struggling with an error that keeps popping up, indicating that the albumName property is undefin ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...

Opting for <button> over <a>

I am currently working with ReactJS in conjunction with a Bootstrap Nav Bar. Bootstrap utilizes an <a> tag for the navigation buttons. I am aiming to have the buttons scroll down to a different component on the page without resorting to using an href ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...

What is the best approach to managing a standard form in React without utilizing AJAX?

Trying to access an endpoint https://api.com/signup.ashx is causing CORS issues. I have been instructed to make the API call without using axios or fetch. Here's what I attempted: const handleSubmit = async (event) => { let error = false ...

Utilizing class references within a method

I have been developing a script that is designed to dynamically load content into multiple predefined DIVs located in the topbar section of my website. Within the Topbar Object, there is an object called Ribbon which contains functions for manipulating on ...

Does JSON hijacking play a role with IE versions greater than 10 or Chrome versions greater than 30?

OWASP suggests wrapping json response with an object rather than returning a direct array. For instance: [{"id":5}] Is this vulnerability still relevant? Could it be exploited? After testing in Chrome, IE, and FF, I couldn't find a way to 'h ...

Display child component automatically upon parent component state update

The main component Dashboard manages the state for each ListItem added to my Watchlist. However, whenever I add an item, it is inserted into the database but only appears when I refresh the browser. class UserDashboard extends React.Component { state = ...

Can a callback in an ES6 class constructor ensure that the promise is either resolved or rejected?

I'm currently puzzled by the concept of using a callback function that always returns an empty object and then passing a parameter to this callback. Visit this link for more information My assumption is that this approach ensures that the Promise wi ...

unable to send array in cookie through express isn't functioning

Currently, I am in the midst of a project that requires me to provide the user with an array. To achieve this, I have been attempting to utilize the res.cookie() function. However, each time I try to pass an array as cookie data, the browser interprets it ...

Could JSON be improved for better space efficiency, or is this the standard format?

Within my code, I am using var team = <?php echo json_encode(get_results("SELECT id,name,title,bio,sord,picfn FROM mems ORDER BY sord")); ?>; This code generates a JavaScript array of objects like: var team = [{"id":"1","name":"somename1","title": ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

Converting a Javascript object to JSON format only once using AngularJS

Is it possible to convert a JavaScript object to JSON using angular.toJson only once in my code? Here is an example: $scope.task.tags = [{"id":22,"tag":"printer","created_at":"2016-03-15" }]; $scope.create = function(task) { tmp.tags = angular.toJson( ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

Getting data from a URL using Node.js and Express: A beginner's guide

Currently, I am facing an issue with extracting the token value from the URL http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8. My get request successfully validates the token and redirects the user to a password reset screen. Howe ...

What is the best way to activate CSS filters on VueJS once the project has been compiled?

While working on a Node server locally, my SVG filter functions properly. However, once I build the project and run it on a server, the filter stops working. This VueJS project is utilizing Webpack as its build tool. The process of building the app invol ...

Is there a way to simulate pressing a keyboard button using jQuery?

Below is the code snippet: $("input").on({ keydown: function(ev) { if (ev.which === 27){ // esc button backspace_emolator(); } else if (ev.which === 8){ // backspace button console.log('backspace button ...

Angular and dropdowns: a perfect match

Imagine having a controller like this: myApp.controller('testCtrl', function ($scope) { $scope.cars = [ { carId: '1', carModel: 'BMW', carOwner: 'Nader' }, { carId: '2', carModel: &apos ...