Home > Net >  Event firing multiple times in Vuejs
Event firing multiple times in Vuejs

Time:07-08

So, I wrote a function that using which the user can upload multiple files.

<input multiple type="file" id="inputFile" ref="fileSelect" @click="uploadfiles"/>

uploadfiles(){     
    'use strict'
  const inputFile = document.getElementById('inputFile')

  console.log(inputFile)
  inputFile!.addEventListener('change',async e => {
    const files  = (e.target as HTMLInputElement).files
    const reader = new FileReader()
    console.log(files)
    console.log(reader)
    // New set of results each time.
    this.results.splice(0)

    for (const file of files!){
      if(file["type"] == "application/json"){
      this.results.push(await this.readjsonfile(reader, file))}
      else if(file["type"]=="text/csv"){
        this.results.push(await this.readcsvfile(reader, file))
      }
      
      }

    })}

Now when I upload a file for the 1st time it works fine, but when I click on the choose files button again to upload another file, it uploads that file twice. I think the problem is that when I click again on choose files I "activate" the uploadfiles function again, which causes the Event Listener to fire twice, but I am not sure how to do it any other way. I am new to JavaScript and vuejs, so any suggestions are greatly appreciated.

Thanks to @Daniel I finally ended up figuring out how to fix this. My final code is

<input multiple type="file" id="inputFile" ref="fileSelect" @change="uploadfiles"/>
uploadfiles(event){     
    'use strict'
    console.log(event)
    //console.log(event.target.files)
    const q = [event.target.files]
    q.forEach(async w => {
      const reader = new FileReader()
      this.results=[]
      for(const file of w){
        if(file["type"] == "application/json"){
      this.results.push(await this.readjsonfile(reader, file))}
      else if(file["type"]=="text/csv"){
        this.results.push(await this.readcsvfile(reader, file))
      }
      }
    })
    console.log(this.results)
    }

CodePudding user response:

The reason is that you're adding inputFile!.addEventListener every time the user clicks on the input form

Instead, if you were to use @change, instead of @click, that should not be happening any more.

example:

<script setup>
  import {ref} from "vue"
  let files = ref([])
  function uploadfiles(event){
    files.value.splice(0);
    [...event.target.files].forEach(async file => {
      // do the logic here
      files.value.push(file)
    })
  }
</script>

<template>
  <input multiple type="file" id="inputFile" ref="fileSelect" @change="uploadfiles"/>
  <pre>{{files}}</pre>
</template>

SFC playground

  • Related