【发布时间】:2021-09-22 05:58:09
【问题描述】:
使用 Vue 3 的 Composition API,我想暂时将本地选择的照片显示为按钮的背景图片。上传后,style.backgroundImage 将恢复为默认值。
我遇到的第一组错误是Object is possibly 'null' 上的photo.value 和e.target。我有条件地解决了这些问题。如果这不是 Vue 3 最佳实践,请告诉我。
我当前面临的错误是e.target.files[0] 上的Property 'files' does not exist on type 'EventTarget'.。这是类型声明问题吗?如何最好地解决这个问题?
在线解决方案(<HTMLInputElement>e.target).files[0] 似乎不适用于 Vue。返回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)
}
}
}
【问题讨论】:
标签: javascript typescript vue.js vuejs3 vue-composition-api