【发布时间】:2021-12-01 06:38:00
【问题描述】:
对于这个愚蠢的问题,我深表歉意,但我正在尝试在上传文件时更改按钮的名称。我通过 TypeScript 更改它的代码是这样的:
const i = (document.querySelector('label') as any).innerText = filename;
上面的代码,在fileName 方法中,将“上传项目文件”文本更改为上传的任何文件的名称。
<div class="row">
<div class="clg6 cmd8 csm10 cxs12" v-if="this.projectFile">
<button
class="button primary outline medium upload">
<label>
<input
type="file"
name="projectFile"
id="fileName"
accept=".xls, .xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
v-on:change="validateFileType(); hashContentMD5(); fileName; getPresignedURL()"/>
<i class="fas fa-cloud-upload"></i>
Upload Project File
</label>
</button>
</div>
</div>
而且它有效。但是,在更改时,它会在我的其他方法被调用时出现错误,例如:
const file = (document.getElementById('fileName')as any).files[0]
出现的错误是
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'files')
删除document.querySelector 会删除错误。这是我第一次遇到这种情况。我该如何解决?
【问题讨论】:
-
为什么不用
ref而不是document.querySelector? -
抱歉,我可能睡眠不足——那会是什么样子? @LucasDavidFerrero
-
不要在 Vue 中直接访问 DOM,除非你必须(这里你不需要),当然不能通过选择器。您可以通过事件访问输入值,而不是访问元素
标签: html typescript vue.js