eight
2025-04-15 589bcdb26f8e9d3e0d5ef46d27acc901c96d50ea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<template>
  <el-upload
    :action="UPLOAD_URL"
    :headers="HEADERS"
    multiple
    :limit="1"
    :file-list="fileList"
    :data="uploadData"
    :on-error="onUploadError"
    :before-upload="onBeforeUpload"
    :on-success="onUploadSuccess"
  >
    <el-button type="primary" plain> 点击上传 </el-button>
    <template #tip>
      <span class="el-upload__tip" style="margin-left: 5px">
        <slot></slot>
      </span>
    </template>
  </el-upload>
</template>
<script lang="ts" setup>
import type { UploadProps, UploadUserFile } from 'element-plus'
import {
  HEADERS,
  UPLOAD_URL,
  UploadData,
  UploadType,
  beforeImageUpload,
  beforeVoiceUpload
} from './upload'
 
const message = useMessage()
 
const props = defineProps<{ type: UploadType }>()
 
const accountId = inject<number>('accountId')
 
const fileList = ref<UploadUserFile[]>([])
const emit = defineEmits<{
  (e: 'uploaded', v: void)
}>()
 
const uploadData: UploadData = reactive({
  type: UploadType.Image,
  title: '',
  introduction: '',
  accountId: accountId!
})
 
/** 上传前检查 */
const onBeforeUpload = props.type === UploadType.Image ? beforeImageUpload : beforeVoiceUpload
 
/** 上传成功处理 */
const onUploadSuccess: UploadProps['onSuccess'] = (res: any) => {
  if (res.code !== 0) {
    message.alertError('上传出错:' + res.msg)
    return false
  }
 
  // 清空上传时的各种数据
  fileList.value = []
  uploadData.title = ''
  uploadData.introduction = ''
 
  message.notifySuccess('上传成功')
  emit('uploaded')
}
 
/** 上传失败处理 */
const onUploadError = (err: Error) => message.error('上传失败: ' + err.message)
</script>
 
<style lang="scss" scoped>
.el-upload__tip {
  margin-left: 5px;
}
</style>