Vue2.6 + TypeScript3.4 项目中使用 this.$refs.fileInput.files.length
报错,提示 files
类型不存在 Property 'files' does not exist on type 'Element | Element[] | Vue | Vue[]'
如下一个 fileChange 函数
private fileChange() { if (this.$refs.fileInput.files.length > 0) { this.file = this.$refs.fileInput.files[0] const reader = new FileReader() const self = this reader.readAsDataURL(this.file) reader.onload = (e: any) => { const dataBase64: any = reader.result self.userInfo.avatar = dataBase64 } } }
template
<input ref="fileInput" type="file" @change="fileChange()" />
在不使用TypeScript时上面的写法可以正常运行的,但是这样的写法在TypeScript 中会报错,终端报错如下
534:40 Property 'files' does not exist on type 'Element | Element[] | Vue | Vue[]'. Property 'files' does not exist on type 'Element'. 532 | private fileChange() { 533 | if (this.$refs.fileInput.files.length > 0) { > 534 | this.file = this.$refs.fileInput.files[0] | ^ 535 | const reader = new FileReader() 536 | const self = this 537 | reader.readAsDataURL(this.file) No lint errors found Version: typescript 3.8.3, tslint 5.20.1 Time: 1413ms App running at: - Local: http://localhost:8080/ - Network: http://192.168.199.172:8080/
解决方式
因为TypeScript需要知道属性是什么类型,这里需要强制类型转换
把 this.$refs.fileInput.files.length
换成 (this.$refs.fileInput as Vue & { files: () => any }).files.length
把 this.file = this.$refs.fileInput.files[0]
换成 const fs: any = (this.$refs.fileInput as Vue & { files: () => any }).files
和 this.file = fs[0]
最后如下效果,代码就可以正常运行了
private fileChange() { if ((this.$refs.fileInput as Vue & { files: () => any }).files.length > 0) { const fs: any = (this.$refs.fileInput as Vue & { files: () => any }).files this.file = fs[0] const reader = new FileReader() const self = this reader.readAsDataURL(this.file) reader.onload = (e: any) => { const dataBase64: any = reader.result self.userInfo.avatar = dataBase64 } } }
参考来源
stackoverflow.com/questions/5…