一、组件编写
<script setup lang="ts">
import { onMounted } from 'vue'
const emit = defineEmits<{
(e: 'upload', data: any): void
}>()
const props = defineProps<{
multiple: boolean
}>()
const dragOver = (e: any) => {
e.stopPropagation()
e.preventDefault()
}
const drop = (e: any) => {
e.stopPropagation()
e.preventDefault()
const files = e.dataTransfer.files
emit('upload', files)
}
const handleUploadFile = async (value: any) => {
const files = value.target.files
emit('upload', files)
}
const handleAddImg = () => {
const input = document.querySelector('#custom-upload') as any
input.click()
}
onMounted(() => {
const dropBox = document.querySelector('#drop') as Element
dropBox.addEventListener('dragover', dragOver, false)
dropBox.addEventListener('drop', drop, false)
})
</script>
<template>
<n-el id="drop" class="flex flex-col justify-center items-center h-full w-full">
<n-el class="flex flex-col justify-center items-center" @click="handleAddImg">
<i-app:upload-img />
<n-el class="flex flex-col items-center mt-7">
<n-el class="flex"
>点击上传图片 <n-el class="text-[#999999] ml-2 mr-2">或 </n-el>拖拽到此区域</n-el
>
</n-el>
</n-el>
<input
id="custom-upload"
ref="fileInput"
class="opacity-0"
type="file"
:multiple="props.multiple || false"
accept=".jpg,.jpeg,.png"
@change="handleUploadFile"
/>
</n-el>
</template>
<style lang="less" scoped></style>
二、页面引入组件
<UploadImgs class="h-[70vh]" :multiple="false" @upload="handleUploadImg" />
......
const handleUploadImg = (files) => {
console.log('debug===>获取到上传的文件',files)
//TODO
}