shinnoske0727
3/24/2020 - 2:17 AM

Drag&Dropで画像のDataURLを返すHooks

import { ref } from '@vue/composition-api'

const useDnDImage = () => {
  const previewSrc = ref('')

  const onDragStart = (e: DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const onDragOver = (e: DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'
  }

  const onDrop = (e: DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    const reader = new FileReader()
    reader.onload = (e: ProgressEvent<FileReader>) => {
      if (e.target) previewSrc.value = e.target.result as string
    }
    if (e.dataTransfer) reader.readAsDataURL(e.dataTransfer.files[0])
  }

  return {
    previewSrc,
    onDragStart,
    onDragOver,
    onDrop
  }
}

export default useImagePreview