<template>
<input ref="inputRef" type="file" class="upload-input" @change="changeFile" />
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const inputRef = ref<null | HTMLInputElement>(null);
const uploadFile = () => {
inputRef.value?.click();
};
const changeFile = () => {
const file = inputRef.value.files[0];
};
return {
inputRef,
changeFile
};
}
});
</script>
const file = inputRef.value.files[0];这个地方总是报对象可能为null,加了!或者强转类型都不行,只有使用any,但是使用any类型检查就没了,这个哪位大佬能帮忙看下
const inputRef = ref<null | HTMLInputElement>(null);
这一句过后inputRef.value
就是null
啊,所以提示信息并没有问题。既然
inputRef.value
可能是null
,那么inputRef.value.files
就有可能取不到,这里要考虑null
的情况。而且就算inputRef.value
不是null
的时候,inputRef.value.files
也有可能是空或者空数组 ——这样就可以了,不过
file
有可能是undefined
哦