我的模板
<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>
我的js
export default {
name: 'UploadComponent',
methods: {
log(str){
console.log(str)
},
dragEntered(e){
// change some styles
},
dropped(e){
console.log(e.dataTransfer.files)
}
}
}
问题: 如果我拖动P元素并将其删除或点击转义它将记录&#34;结束&#34;。如果我从桌面上找到一个文件并将其放回桌面或者点击转义或丢弃它,dragend事件就不会触发它并且不会记录任何内容
答案 0 :(得分:1)
我可能迟到了几年,但也许其他人会发现这很有用。
请注意,将文件从操作系统拖到浏览器时不会触发dragstart和dragend事件。
因此dragend事件将无法正常工作,但还有另一种解决方案,dragover事件会迅速触发,因此您可以设置超时以清除叠加层(如果该层停止触发一秒钟),如下所示:
<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>