1. Basic code

<template>
	<div id="drop-area" :class="dropActive ? 'drop-active' : ''">
	</div>
</template>
<script>
export default {
	name:'index'.data(){
		return {
			dropActive:false}},methods: {dropEvent(e) {
	        this.dropActive = false
	        e.stopPropagation()
	        e.preventDefault()
	        this.uploadFile(e.dataTransfer.files)
	    },
	    uploadFile (file) { // Render the uploaded file
	      console.log(file[0].'file')
	      if (file && file.length) {
	        // Save locally or upload to the server
	      }
	    },
	},
	mounted () {
		let dropArea = document.getElementById('drop-area')
	    dropArea.addEventListener('drop'.this.dropEvent, false)
	    dropArea.addEventListener('dragleave'.(e) = > {
	      e.stopPropagation()
	      e.preventDefault()
	      this.dropActive = false
	    })
	    dropArea.addEventListener('dragenter'.(e) = > {
	      e.stopPropagation()
	      e.preventDefault()
	      this.dropActive = true
	    })
	    dropArea.addEventListener('dragover'.(e) = > {
	      e.stopPropagation()
	      e.preventDefault()
	      this.dropActive = true
	    })
	}
}
<script>
<style scoped>
#drop-area{
	width:300px;
	height:300px;
	background-color:#fff;
	border:1px solid red;
}
.drop-active{
	background-color: rgba(231.234.246.0.8);
}
</style>
Copy the code

Listen for drag events

Vue mounted(){} locate a mounted file and drag it to an area where id= “drop-area”. When the file is in the drag area for the first time, the dragenter event is triggered. 2. When the file is dragged back and forth in the drag area, the dragover event is continuously triggered. The dragleave event is constantly triggered to implement drag uploads, and we only need to care about the drop event. However, the other three events also need to be listened for in order to prevent default browser behavior. If you don’t, the browser automatically downloads the file when you drag it to the browser (the default behavior) and the drop event does not occur.

The this.dropEvent function is written in the methods:{} project. The listening event will have a File callback.

Copyright statement

This article is an original article BY CSDN blogger “Weixin_44635214”. It follows CC 4.0 BY-SA copyright agreement. Please attach the source link and this statement for reprint. Original link: blog.csdn.net/weixin_4463…