UploadInput.vue 991 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <template>
  2. <div class="upload-input" @click="handleClick()">
  3. <slot></slot>
  4. <input
  5. class="file-input"
  6. type="file"
  7. name="upload"
  8. ref="inputRef"
  9. :accept="accept"
  10. @change="$event => handleChange($event)"
  11. >
  12. </div>
  13. </template>
  14. <script lang="ts">
  15. import { defineComponent, ref } from 'vue'
  16. export default defineComponent({
  17. name: 'upload-input',
  18. props: {
  19. accept: {
  20. type: String,
  21. default: 'image/*',
  22. },
  23. },
  24. setup(props, { emit }) {
  25. const inputRef = ref<HTMLInputElement | null>(null)
  26. const handleClick = () => {
  27. if(!inputRef.value) return
  28. inputRef.value.value = ''
  29. inputRef.value.click()
  30. }
  31. const handleChange = (e: InputEvent) => {
  32. const files = (e.target as HTMLInputElement).files
  33. if(files) emit('change', files)
  34. }
  35. return {
  36. handleClick,
  37. handleChange,
  38. }
  39. },
  40. })
  41. </script>
  42. <style lang="scss" scoped>
  43. .file-input {
  44. display: none;
  45. }
  46. </style>