Vue2 ElementUI Upload组件http-request用法
一、示例代码
<template><el-uploadref="upload"action="":auto-upload="false":file-list="upload.fileList":accept="upload.accept":on-remove="removeFile":on-change="verifyFile":http-request="uploadFile":on-success="uploadSuccess":on-error="uploadError"><el-button slot="trigger" size="small">选择文件</el-button><el-button type="primary" size="small" :disabled="uploadDisabled" :loading="upload.loading" style="margin-left: 10px;" @click="confirmUpload">上传文件</el-button><div slot="tip" style="font-size: 12px;">只能上传xls/xlsx文件</div></el-upload>
</template>
<script>
export default {data () {upload: {loading: false,accept: '.xls,.xlsx',fileList: []}},computed: {uploadTypeErrorMessage () {return `只能上传 ${this.upload.accept.split(',')} 格式的文件`;},uploadDisabled () {return this.upload.fileList.length===0;}},methods: {removeFile () {let index = this.upload.fileList.findIndex(li =>li.uid===file.uid);index===-1?'':this.upload.fileList.splice(index, 1);},verifyFile (file) {if(file.status==='ready') {this.uploadDisabled?this.upload.fileList.push(file):this.upload.fileList.splice(0, 1, file);if(!['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(file.raw.type)) {this.$message.error(this.uploadTypeErrorMessage);this.removeFile(file);}}},confirmUpload () {this.$refs.upload.submit();},uploadFile (options) {this.upload.loading = true;uploadFile({ //自定义接口file: options.file}).then(res => {options.onSuccess(res);}).catch(error => {options.onError(error);}).finally(() => {this.upload.loading = false;});},uploadSuccess (res) {},uploadError (error) {this.$message.error(error);}}
}
</script>