With Vue 3's Composition API, I am aiming to dynamically display the selected photo as the background image of a button temporarily. Upon uploading, the button's background image should revert back to its default state.
Initially, I encountered errors such as 'Object is possibly null'
with photo.value
and e.target
. I managed to resolve these issues using conditional statements. Please advise if this approach aligns with Vue 3 best practices.
Currently, I am facing an error stating
'Property 'files' does not exist on type 'EventTarget''
in relation to e.target.files[0]
. Could this be a type declaration problem? What would be the optimal way to address this issue?
The proposed online solution
(<HTMLInputElement>e.target).files[0]
appears ineffective in a Vue context, resulting in the message 'Object is possibly null'
.
<template>
<button ref="photo" @click="uploadPhoto"></button>
<input type="file" ref="photoInput" @change="showTempPhoto" style="display: none" />
</template>
setup(){
const photo = ref<HTMLDivElement | null>(null)
const photoInput = ref<HTMLInputElement | null>(null)
const uploadPhoto = () => {
photoInput.value?.click()
}
const showTempPhoto = (e: Event) => {
if (photo.value && e.target){
const url = URL.createObjectURL(e.target.files[0])
photo.value.style.backgroundImage = url
photo.value.onload = () => URL.revokeObjectURL(url)
}
}
}