vue3 + naiveui | 实现input自定义上传图片(可拖拽)

image.png

一、组件编写

<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
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值