真的是比較懶于寫博文非剃,下面來說一下el-upload組件在使用中遇到的一些坑:
原el-upload組件使用 :http_request 來綁定自定義上傳函數(shù),如何不通過按鈕而是在完成一些操作以后自動觸發(fā)上傳事件呢刚梭?
答: 使用 :on-change 綁定一個方法,該方法攜帶參數(shù)(file, fileList), 在文件狀態(tài)改變時調(diào)用,即在選中文件后堪唐,上傳文件成功,上傳文件失敗時都會調(diào)用翎蹈,在這個方法內(nèi)完成文件上傳前的操作之后淮菠,使用this.$refs.upload.submit() 完成上傳組件自定義上傳方法的調(diào)用;當然荤堪,前提是在使用<el-upload>組件時在其中定義了 ref= upload 的屬性合陵。<el-upload>組件自帶的上傳操作,action定義默認上傳的接口逞力,同時可以通過 :data=XXX 進行默認上傳攜帶額外參數(shù)的定義曙寡,但是不能通過 this.refs.upload.data 操作在文件上傳之前進行data屬性的設置。
解釋: 正確來說寇荧,是可以修改成功的举庶。控制臺打印 this.$refs.upload.data 的確是可以打印出設置的正確值揩抡,但是控制臺查看觸發(fā)的默認上傳操作户侥,卻無法正確設置每一次上傳的攜帶的額外參數(shù)值。(具體原因不詳峦嗤,但是感覺是異步操作的原因蕊唐。data屬性在有定義的初始值,在 on-change 綁定的方法中重新設置的額外參數(shù)烁设,但沒有立即生效替梨,而是等到下一個文件上傳才生效)
具體代碼:
<el-upload
ref="upload"
:action="fileAction"
:headers="myHeaders"
:data="type"
drag
:auto-upload="false"
accept=".apk, .zip, .rar"
:file-list="fileList"
:http-request="uploadFile"
:on-error="uploaderr"
:on-success="succe"
:on-change="handleExceed">
<i class="el-icon-upload"></i>
<div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
<div class="el-upload__tip" slot="tip">上傳應用新版本即可自動獲取下載鏈接(只限于apk, rar, zip文件)</div>
</el-upload>
數(shù)據(jù):
type: {type: 'apk'}
//選擇文件時會替換掉上一個文件 狀態(tài)改變的鉤子
handleExceed(files, fileList) {
if(files.name.indexOf(".zip")>0){
//this.type = "zip"
this.$refs.upload.data= {types: "zip"}
console.log("上傳組件自定義參數(shù)",this.$refs.upload.data)
//this.$refs.upload.submit();
}
else if(files.name.indexOf(".rar")>0){
//this.type = "rar"
this.$refs.upload.data = {types: "rar"}
console.log("上傳組件自定義參數(shù)",this.$refs.upload.data)
//this.$refs.upload.submit();
}else if(files.name.indexOf(".apk")>0){
//this.type = "apk"
this.$refs.upload.data = {types:"apk"}
console.log("上傳組件自定義參數(shù)",this.$refs.upload.data)
//this.$refs.upload.submit();
}
this.fileList = fileList.slice(-1);
},
當我選擇的文件后綴是.zip時装黑,控制臺查看到的請求攜帶的參數(shù)還是 apk(初始設定值)副瀑,當我繼續(xù)選擇一個rar文件時,控制臺查看的攜帶參數(shù)是zip,而不是rar....
所以我最終選擇了自定義上傳方法恋谭。