Skip to content

useDropZone

创建一个可以删除文件的区域。

¥Create a zone where files can be dropped.

警告

由于 Safari 浏览器的限制,文件类型验证只能在 drop 事件期间进行,而不能在 drag 事件期间进行。因此,在 Safari 中,无论文件类型如何,在拖拽操作过程中,isOverDropZone 的值始终为 true

¥Due to Safari browser limitations, file type validation is only possible during the drop event, not during drag events. As a result, the isOverDropZone value will always be true during drag operations in Safari, regardless of file type.

示例

Drop files from your computer on to drop zones

General DropZone
isOverDropZone: false
Image DropZone
isOverDropZone: false

用法

¥Usage

vue
<script setup lang="ts">
import { useDropZone } from '@vueuse/core'

const dropZoneRef = ref<HTMLDivElement>()

function onDrop(files: File[] | null) {
  // called when files are dropped on zone
}

const { isOverDropZone } = useDropZone(dropZoneRef, {
  onDrop,
  // specify the types of data to be received.
  dataTypes: ['image/jpeg'],
  // control multi-file drop
  multiple: true,
  // whether to prevent default behavior for unhandled events
  preventDefaultForUnhandled: false,
})
</script>

<template>
  <div ref="dropZoneRef">
    Drop files here
  </div>
</template>

类型声明

typescript
export interface UseDropZoneReturn {
  files: Ref<File[] | null>
  isOverDropZone: Ref<boolean>
}
export interface UseDropZoneOptions {
  /**
   * Allowed data types, if not set, all data types are allowed.
   * Also can be a function to check the data types.
   */
  dataTypes?:
    | MaybeRef<readonly string[]>
    | ((types: readonly string[]) => boolean)
  onDrop?: (files: File[] | null, event: DragEvent) => void
  onEnter?: (files: File[] | null, event: DragEvent) => void
  onLeave?: (files: File[] | null, event: DragEvent) => void
  onOver?: (files: File[] | null, event: DragEvent) => void
  /**
   * Allow multiple files to be dropped. Defaults to true.
   */
  multiple?: boolean
  /**
   * Prevent default behavior for unhandled events. Defaults to false.
   */
  preventDefaultForUnhandled?: boolean
}
export declare function useDropZone(
  target: MaybeRefOrGetter<HTMLElement | null | undefined>,
  options?: UseDropZoneOptions | UseDropZoneOptions["onDrop"],
): UseDropZoneReturn

源代码

源代码示例文档

变更日志

v12.3.0 on 1/2/2025
b01cf - fix: validate all file types individually when dropping multiple files (#4325)
v12.1.0 on 12/22/2024
df363 - fix: update type to allow readonly array param (#4319)

VueUse 中文网 - 粤ICP备13048890号