Skip to content

Commit

Permalink
feat(useFileDialog): add listener for file change events (#2893)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alfred-Skyblue committed Mar 23, 2023
1 parent c641d55 commit 5e697ba
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
5 changes: 4 additions & 1 deletion packages/core/useFileDialog/demo.vue
@@ -1,7 +1,10 @@
<script setup lang="ts">
import { useFileDialog } from '.'
const { files, open, reset } = useFileDialog()
const { files, open, reset, onChange } = useFileDialog()
onChange((files) => {
/** do something with files */
})
</script>

<template>
Expand Down
6 changes: 5 additions & 1 deletion packages/core/useFileDialog/index.md
Expand Up @@ -11,7 +11,11 @@ Open file dialog with ease.
```ts
import { useFileDialog } from '@vueuse/core'

const { files, open, reset } = useFileDialog()
const { files, open, reset, onChange } = useFileDialog()

onChange((files) => {
/** do something with files */
})
```

```html
Expand Down
8 changes: 6 additions & 2 deletions packages/core/useFileDialog/index.ts
@@ -1,4 +1,5 @@
import { hasOwn } from '@vueuse/shared'
import type { EventHookOn } from '@vueuse/shared'
import { createEventHook, hasOwn } from '@vueuse/shared'
import { type Ref, readonly, ref } from 'vue-demi'
import type { ConfigurableDocument } from '../_configurable'
import { defaultDocument } from '../_configurable'
Expand Down Expand Up @@ -28,6 +29,7 @@ export interface UseFileDialogReturn {
files: Ref<FileList | null>
open: (localOptions?: Partial<UseFileDialogOptions>) => void
reset: () => void
onChange: EventHookOn<FileList | null>
}

/**
Expand All @@ -42,7 +44,7 @@ export function useFileDialog(options: UseFileDialogOptions = {}): UseFileDialog
} = options

const files = ref<FileList | null>(null)

const { on: onChange, trigger } = createEventHook()
let input: HTMLInputElement | undefined
if (document) {
input = document.createElement('input')
Expand All @@ -51,6 +53,7 @@ export function useFileDialog(options: UseFileDialogOptions = {}): UseFileDialog
input.onchange = (event: Event) => {
const result = event.target as HTMLInputElement
files.value = result.files
trigger(files.value)
}
}

Expand Down Expand Up @@ -80,5 +83,6 @@ export function useFileDialog(options: UseFileDialogOptions = {}): UseFileDialog
files: readonly(files),
open,
reset,
onChange,
}
}

0 comments on commit 5e697ba

Please sign in to comment.