需求是在一个表格数据里面做文件上传按钮,需要在文件上传的时候传递当前行的主键id。el-upload组件默认提供的函数都没能实现这个功能,于是对函数的写法稍加更改以实现传递额外参数的功能。
HTML部分:
<el-upload
<!-- 禁止自动上传,所以不在这里填写上传地址 -->
:action="''"
<!-- 设置文件样式按钮的样式和其他按钮一行显示 -->
style="display: inline-block"
<!-- 修改文件状态改变时的钩子写法,实现多传递一个额外参数功能 -->
:on-change="(file, fileList) => { return fileChange(file, fileList, scope.row.id)}"
:file-list="fileList"
<!-- 禁用自动上传 -->
:auto-upload="false"
:show-file-list="false">
<el-button size="mini" type="text">上传</el-button>
</el-upload>
JavaScript部分:
fileChange(file, fileList, id) {
this.fileList = fileList.slice(-3);
this.handleUpload(file, fileList, id)
},
handleUpload(file, fileList, id) {
let data = new FormData()
data.append('file', file.raw)
upload(data, id).then(response => {
console.log('上传结果:', response)
})
}