80 lines
1.8 KiB
Vue
Raw Normal View History

2023-04-15 15:59:33 +08:00
<template>
<el-upload
:action="UPLOAD_URL"
:headers="HEADERS"
multiple
:limit="1"
:file-list="fileList"
:data="uploadData"
2023-04-16 22:32:59 +08:00
:on-progress="(isUploading = true)"
:on-error="onUploadError"
:before-upload="onBeforeUpload"
:on-success="onUploadSuccess"
2023-04-15 15:59:33 +08:00
>
2023-04-16 22:32:59 +08:00
<el-button type="primary" plain :loading="isUploading" :disabled="isUploading">
{{ isUploading ? '正在上传' : '点击上传' }}
2023-04-15 15:59:33 +08:00
</el-button>
<template #tip>
<span class="el-upload__tip" style="margin-left: 5px">
<slot></slot>
</span>
</template>
</el-upload>
</template>
<script setup lang="ts">
import type { UploadProps, UploadUserFile } from 'element-plus'
import {
HEADERS,
UPLOAD_URL,
UploadData,
MaterialType,
beforeImageUpload,
beforeVoiceUpload
} from './upload'
const message = useMessage()
2023-04-15 16:54:36 +08:00
const props = defineProps<{ type: MaterialType }>()
2023-04-15 15:59:33 +08:00
const fileList = ref<UploadUserFile[]>([])
const emit = defineEmits<{
(e: 'uploaded', v: void)
}>()
const uploadData: UploadData = reactive({
type: MaterialType.Image,
title: '',
introduction: ''
})
2023-04-16 22:32:59 +08:00
const isUploading = ref(false)
2023-04-15 15:59:33 +08:00
2023-04-16 22:32:59 +08:00
/** 上传前检查 */
const onBeforeUpload = props.type === MaterialType.Image ? beforeImageUpload : beforeVoiceUpload
2023-04-15 15:59:33 +08:00
2023-04-16 22:32:59 +08:00
/** 上传成功处理 */
const onUploadSuccess: UploadProps['onSuccess'] = (res: any) => {
2023-04-15 15:59:33 +08:00
if (res.code !== 0) {
message.alertError('上传出错:' + res.msg)
return false
}
// 清空上传时的各种数据
fileList.value = []
uploadData.title = ''
uploadData.introduction = ''
message.notifySuccess('上传成功')
2023-04-16 22:32:59 +08:00
isUploading.value = false
2023-04-15 15:59:33 +08:00
emit('uploaded')
}
2023-04-16 22:32:59 +08:00
/** 上传失败处理 */
const onUploadError = (err: Error) => message.error('上传失败: ' + err.message)
2023-04-15 15:59:33 +08:00
</script>
2023-04-16 22:32:59 +08:00
<style lang="scss" scoped>
.el-upload__tip {
margin-left: 5px;
}
</style>