【问题标题】:Vue 3 Typescript Composition API: Property 'files' does not exist on type 'EventTarget'Vue 3 Typescript Composition API:“EventTarget”类型上不存在属性“文件”
【发布时间】: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


    【解决方案1】:

    Event 类可能有也可能没有如下所示的目标:

    let my_event = new Event('event_type');
    console.log(my_event.target)
    
    // outputs null
    

    并且打字稿不知道目标的元素类型或者它是否不为空;因此,如果 target 不是 null 并将 e.target 转换为 HTMLInputElement,则必须明确检查:

    const showTempPhoto = (e: Event) => {
        if (photo.value && e.target !== null){
            const url = URL.createObjectURL((<HTMLInputElement>e.target).files[0])
            photo.value.style.backgroundImage = url
            photo.value.onload = () => URL.revokeObjectURL(url)
        }
    }
    

    【讨论】:

    • 这是我尝试过的在线解决方案,但收到了Object is possibly 'null'.我相信这可能是一个Vue特定的问题。
    • 您是否明确检查过 null ?你能显示完整的错误日志吗?你用的是什么版本的ts?
    • 想通了。我需要解构 url 声明。不过,感谢您的帮助。
    【解决方案2】:

    解构 url 声明帮助我解决了这个问题。

    const target = <HTMLInputElement>e.target
    

    后跟null 支票,

    const url = URL.createObjectURL(target.files && target.files[0])
    

    最后清理了backgroundImage 分配

    photo.value.style.backgroundImage = `url('${url}')`
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2019-03-07
      • 2019-08-18
      • 2017-11-03
      • 1970-01-01
      • 2019-01-28
      • 2017-06-23
      相关资源
      最近更新 更多