1.問題描述
element中upload為我們提供了強大的上傳功能,往往我們可能用作單獨上傳某個文件。但是在一個列表中,需要有多個同種類型的上傳組件,這時我們無法根據索引,將上傳的文件放置在對應的數組索引中,例如:
<ul>
<li v-for="(item, index) in List" :key="index">
<el-upload></el-upload>
</li>
</ul>
無法將學習資料1中上傳的文件對應到學習資料數組中
image.png
2.如何解決?
思路,在觸發上傳或者上傳成功時,在鉤子函數中傳入當前索引,上傳成功后,根據索引,把上傳的文件放到數組里,這是我能想到最通俗易懂的方法。
首先我們來看下element中upload的API
image.png
從以上圖片,我們可以看到,上傳的這幾個鉤子里面,都沒有可以加的額外參數,那么直接在鉤子中加入索引是不現實的。
2.1解決一:修改源碼,在on-success回調中增加index索引
找到this.handleSuccess這個函數,你會發現源碼中只有三個參數,res, file,和this.uploadFiles,這與官方文檔中function(response, file, fileList)參數是一致的,現在我們來看下在這里面定義一個index參數后,on-success回調中,返回的參數是什么
handleSuccess: function handleSuccess(res, rawFile) {
var file = this.getFile(rawFile);
if (file) {
file.status = 'success';
file.response = res;
this.onSuccess(res, file, this.uploadFiles);
this.onChange(file, this.uploadFiles);
}
},
- 項目里面找到node_modules/element-ui/lib/element-ui.common.js
- 在props里面加一個要父組件傳過來的參數bindIndex
onSuccess: {
type: Function,
default: noop
},
bindIndex: null,
onProgress: {
type: Function,
default: noop
},
- 可以在上面handleSuccess這個函數中加入這個參數
this.onSuccess(res, file, this.uploadFiles, this.bindIndex);
- 現在我們可以在el-upload中傳入這個參數了
<ul>
<li v-for="(item, index) in List" :key="index">
<el-upload :bindIndex="index" :on-success="handleSuccess"></el-upload>
</li>
</ul>
- 現在我們可以來看看handleSuccess(res,)這個回調里面參數會打印出什么
handleLearnDataSuccess (res, file, fileList, index) {
console.log(res, file, fileList, index)
let dialog = this.dialog
dialog.learningSource[index].content = {
image_path: res.url,
name: file.name
}
dialog.learningSource[index].file.push(file)
},
這就是我們要拿到的index
image.png
但是這種方法是有弊端的,他實現的原理是修改包文件,但是方法使得其他協同工作的同事也要修改代碼,才能正常運行。
2.2解決二:在調用回調時二次封裝,把默認的參數和自己新增的參數作為一個新的函數返回
這里的index就是我們v-for出來的index,調用哪個upload,就把相對應的index傳進去,上傳成功后,我們是不是就可以把文件與index聯系起來了呢
:on-success="(res,file)=>{return handleLearnDataSuccess(res,file,index)}"
當然,這里用的是es6寫法,可能IE某些版本并不支持這種寫法,我們可以轉換一下,寫成普通函數
:on-success="function (res,file) {return handleLearnDataSuccess(res,file,index)}"
3.總結
解決問題的方法有很多種,但是要找到一個適合我們自己的才是最重要的。簡單總結下關于解決element-ui 中upload組件使用多個時無法綁定對應的元素這個問題,我們可以有一下幾種方式:
- 修改源碼,在回調中加入索引參數
- 調用鉤子函數時,把自己新增參數與原有參數作為一個新的函數返回