Vue 2中如何通过点击事件获取数组rowKey并实现对应文件下载
Vue2 + Element UI 表格下载按钮获取当前行数据解决方案
1. 确认表格row-key绑定
先确保你的el-table已正确绑定row-key属性,和数据中的rowKey字段对应:
<el-table :data="numberList" row-key="rowKey" >
2. 操作列直接传递当前行数据
不用绕去数组里查找,点击下载图标时,通过表格作用域插槽直接拿到当前行对象:
<el-table-column label="操作"> <template slot-scope="scope"> <i class="el-icon-download" style="cursor: pointer;" @click="handleDownload(scope.row)" ></i> </template> </el-table-column>
3. 编写下载方法,直接使用传入的行数据
在methods里实现下载逻辑,直接调用api接口并使用当前行的rowKey和label:
import { downloadFile } from '@/api/yourApiFile' // 引入api文件夹中的下载接口 export default { data() { return { numberList: [] // 你的数据数组 } }, methods: { async handleDownload(row) { try { // 传入当前行的rowKey作为文件标识调用下载接口 const res = await downloadFile(row.rowKey) // 处理文件流下载 const blob = new Blob([res.data], { type: res.headers['content-type'] }) const downloadUrl = window.URL.createObjectURL(blob) const a = document.createElement('a') a.href = downloadUrl a.download = row.label // 用当前行的文件名作为下载文件名 a.click() window.URL.revokeObjectURL(downloadUrl) } catch (err) { console.error('下载出错:', err) this.$message.error('文件下载失败,请稍后重试') } } } }
关于之前find方法出错的说明
你之前用this.numberList.find()只能拿到第一个元素,大概率是find的匹配条件写得有问题(比如条件始终为true,或者匹配字段不对应),但直接通过scope.row获取当前行数据是最直接可靠的方式,完全不需要二次查找数组。
内容的提问来源于stack exchange,提问作者Will Tham
相关产品推荐
相关产品推荐

