Vue实现带进度条的文件拖动上传功能实现带进度条的文件拖动上传功能
主要介绍了Vue实现带进度条的文件拖动上传功能,本文通过实例代码给大家介绍的非常详细,具有参考借鉴价
值,需要的朋友可以参考下
1. 基本界面基本界面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet">
<script src="https://cdn.bootcss.com/vue/2.5.13/vue.min.js"></script>
<style>
.dropbox {
border: .25rem dashed #007bff;
min-height: 5rem;
}
</style>
<title>Document</title>
</head>
<body>
<div id="app" class="m-5">
<div class="dropbox p-3">
<h2 class="text-center">把要上传的文件拖动到这里</h2>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {},
methods: {},
mounted: function () {}
});
</script>
</body>
</html>
2. 检测拖动事件检测拖动事件
首先让页面支持文件拖拽,在 Vue 的 mounted() 函数中添加代码:
mounted: function () {
var dropbox = document.querySelector('.dropbox');
dropbox.addEventListener('dragenter', this.onDrag, false);
dropbox.addEventListener('dragover', this.onDrag, false);
dropbox.addEventListener('drop', this.onDrop, false);
}
当把文件拖动到浏览器的拖动区域时,会触发三种事件:
1. 文件第一次进入拖动区时,触发 dragenter 事件
2. 文件在拖动区来回拖拽时,不断触发 dragover 事件
3. 文件已经在拖动区,并松开鼠标时,触发 drop 事件
实现拖动上传,我们只需要关心 drop 事件。不过另外两个事件也需要监听,目的是阻止浏览器默认行为。如果不阻止,那么
把文件拖到浏览器时,浏览器就会自动下载这个文件(默认行为),drop 事件触发不出来。
事件的监听函数添加在 Vue 的 methods 对象中:
methods: {
uploadFile: function (file) {
console.log(file);
},
onDrag: function (e) {
e.stopPropagation();
e.preventDefault();
评论5