简体   繁体   中英

DragEnd event not fired for files

My template:

<div class="upload-component" @dragend="log('end')" @dragenter="dragEntered" @drop.prevent @dragover.prevent>
    <div class="zone" @drop="dropped">
        
    </div>
    <p draggable="true">drag me</p>
</div>

My js:

export default {
        name: 'UploadComponent',
        methods: {
            log(str){
                console.log(str)
            },
            dragEntered(e){
                // change some styles
            },
            dropped(e){
                console.log(e.dataTransfer.files)
            }
        }
    }

The problem:
If I drag the P element and drop it or hit escape it will log "end". If I come with a file from my desktop and put it back on desktop or hit escape or drop it, the dragend event wont fire and it wont log anything

I'm probably a few years late but maybe someone else will find this useful.

Note that dragstart and dragend events are not fired when dragging a file into the browser from the OS.

Source

So dragend event won't work but there's another solution, dragover event fires rapidly so you can set a timeout to clear the overlay if it stops firing for a second like this:

<template>
  <div class="advice-documents">
    <div
      v-if="isDragOverlayVisible"
      class="advice-documents__drop-zone"
    >
      <span>drop file to upload</span>
    </div>
  </div>
</template>

<script>
export default {
  data: () => ({
    isDragOverlayVisible: false,
    dragOverTimeout: undefined,
  }),

  created() {
    document.addEventListener('dragover', this.handleDragover)
    document.addEventListener('drop', this.handleDrop)
  },

  beforeDestroy() {
    document.removeEventListener('dragover', this.handleDragover)
    document.removeEventListener('drop', this.handleDrop)
  },

  methods: {
    handleDrop(event) {
      event.preventDefault()
      this.isDragOverlayVisible = false
    },

    handleDragover(event) {
      event.preventDefault()
      this.isDragOverlayVisible = true
      console.log('dragover')
      clearTimeout(this.dragOverTimeout)
      this.dragOverTimeout = setTimeout(() => {
        this.isDragOverlayVisible = false
      }, 1000)
    },
  },
}
</script>

<style>
.advice-documents__drop-zone {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.7);
  color: var(--aab-light-green);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8vmin;
  z-index: 1;
}
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM