BootstrapVue中如何将b-button绑定隐藏file类型input实现文件上传
问题原因
- 你当前的
selectFile方法仅读取了ref对应的DOM元素,没有调用click()方法主动触发文件选择弹窗,所以点击按钮没有反应 - 由于你是在
v-for循环内使用ref,Vue会把同名ref收集为数组,直接调用this.$refs.file无法定位到当前点击按钮对应的隐藏input元素
修复代码
模板部分(v-for循环内)
<div v-for="(item, index) in 你的循环数组" :key="index"> <b-button @click="selectFile(index)" variant="success"> Upload </b-button> <input type="file" ref="fileList" style="display: none;" @change="onFileSelected($event, index)" /> </div>
JS方法部分
methods: { selectFile(index) { // 取当前索引对应的隐藏input,触发点击弹出文件选择框 this.$refs.fileList[index].click() }, onFileSelected(event, index) { // 获取选中的文件 const targetFile = event.target.files[0] // 这里写你的文件处理/上传逻辑,用index和循环内的条目绑定 this.你的循环数组[index].uploadFile = targetFile // 可选:清空input值,解决重复选择同一个文件不触发change事件的问题 event.target.value = '' } }
内容的提问来源于stack exchange,提问作者patrick96
相关产品推荐
相关产品推荐

