點燈坊

失くすものさえない今が強くなるチャンスよ

Uploading File by Vue

Sam Xiao's Avatar 2022-11-10

We can upload the file by Vue without Web API.

Version

Vue 3.2

Upload

upload000

The file is uploaded by Alpine.

<template>
  <input type="file" ref="uploadFile" @change="onChange" />
</template>

<script setup>
import { ref } from 'vue'

let uploadFile = ref(null)

let onChange = () => {
  let file = uploadFile.value.files[0]
  console.log(file.name)
}
</script>

Line 2

<input type="file" ref="uploadFile" @change="onChange" />
  • ref:define a reference to access the DOM element

Line 8

let uploadFile = ref(null)
  • Use ref() to define uploadFile Reactive Reference to access the DOM element

 

Line 10

let onChange = () => {
  let file = uploadFile.value.files[0]
  console.log(file.name)
}
  • Use uploadFile.value to access DOM element
  • files is Array. We can get the file from the first element of the files Array

$event

<template>
  <input type="file" @change="onChange($event)" />
</template>

<script setup>
let onChange = ({ target: files }) => {
  let file = files[0]
  console.log(file.name)
}
</script>

Line 2

<input type="file" @change="onChange($event)" />
  • Use $event to pass event Object to onChange()

Line 6

let onChange = ({ target: files }) => {
  let file = files[0]
  console.log(file.name)
}
  • Destructure files from parameter
  • files is Array. We can get the file from the first element of the files Array

Conclusion

  • We can use $event to prevent using Reactive Reference to access the DOM element