基于Vue3文件拖拽上传功能实现
明知山_ 人气:0文件上成功能在我们的身边经常遇到,下面小编通过实例代码给大家分享实现方法,效果图如下所示:
<template> <div :class="['drag', { 'drag-active': active }]" ref="drag"> <p class="drag-title">未选择文件/文件夹</p> <p class="drag-subtile"> 支持拖拽到此区域上传,支持选择多个文件/文件夹 <br /> 单个文件夹最大支持512GB </p> </div> </template> <script setup> import { ref, onMounted, onBeforeUnmount } from 'vue' const drag = ref(null) const active = ref(false) onMounted(() => { drag.value.addEventListener('drop', handleDrop) drag.value.addEventListener('dragleave', (e) => { active.value = false e.preventDefault() }) drag.value.addEventListener('dragenter', (e) => { active.value = true e.preventDefault() }) drag.value.addEventListener('dragover', (e) => { active.value = true e.preventDefault() }) }) onBeforeUnmount(() => { drag.value.removeEventListener('drop', handleDrop) }) const emit = defineEmits(["file"]) const handleDrop = (e) => { e.preventDefault() active.value = false emit("file", Array.from(e.dataTransfer.files)) } </script> <style lang="scss" scoped> .drag { height: 220px; border: 1px dashed #DEDEDE; border-radius: 4px; display: flex; align-items: center; flex-direction: column; justify-content: center; &-active { border: 1px dashed #2260FF; } &-title { font-size: 14px; } &-subtile { font-size: 12px; color: #999999; margin-top: 30px; text-align: center; line-height: unset; } } </style>
加载全部内容