We can upload the file by Vue without Web API.
Version
Vue 3.2
Upload
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 defineuploadFile
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 thefiles
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 passevent
Object toonChange()
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 thefiles
Array
Conclusion
- We can use
$event
to prevent using Reactive Reference to access the DOM element