<!-- 子组件 -->
<template>
<el-upload
:disabled="uploading"
:loading="uploading"
:action="url"
:on-success="uploadCallback"
:on-error="errorTips"
:show-file-list="false"
:before-upload="setUploadLimit"
:auto-upload="true"
>
<el-button
size="small"
type="primary"
>
{{ name }}
</el-button>
</el-upload>
</template>
<script>
import { defineComponent, getCurrentInstance, ref } from '@vue/composition-api';
export default defineComponent({
name: 'ExcelUpload',
props: {
url: {
type: String,
require: true,
default: '',
},
name: {
type: String,
default: '点击上传',
},
},
setup(props, { emit }) {
const { proxy: _this } = getCurrentInstance();
const uploading = ref(false);
// 关闭loading
function turnUploadingToFalse() {
setTimeout(() => {
uploading.value = false;
}, 1500);
}
// 文件上传成功时的钩子
function uploadCallback(r) {
if (r.code === 0) {
emit('uploadSuccess', r);
} else {
_this.$message.error(r.message || r.msg || '导入失败,请重试');
}
turnUploadingToFalse();
}
// 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
function setUploadLimit(file) {
uploading.value = true;
try {
let msg;
if (!/\.xls|xlsx$/.test(file.name)) {
msg = '文件不是excel格式(.xlsx, .xls)';
}
if (file.size >= 1024 * 1024) {
msg = '文件大小超过1M,请确保单次上传数据不要过多';
}
if (msg) {
turnUploadingToFalse();
_this.$message({
message: msg,
type: 'error',
});
return false;
}
} catch (error) {
_this.$alert('文件格式不正确,建议下载模板比对');
turnUploadingToFalse();
return false;
}
return true;
}
// 文件上传失败时的钩子
function errorTips(err) {
console.log(err);
}
return {
uploading,
turnUploadingToFalse,
uploadCallback,
setUploadLimit,
errorTips,
};
},
});
</script>
<!-- 父组件中使用 -->
<ExcelUpload
class="inline-block"
name="上传商品清单"
:url="'你要上传的地址,大概率就是后端给的接口'"
@uploadSuccess="uploadCommodityList()"
/>
// 上传成功后拿到数据,该干啥干啥
function uploadCommodityList(data) {
console.log(data);
}