因为在使用场景中可能会用到多个文件上传,如果每个都一个一个写慢慢就堆成ss了,
使用方法直接在父组件中v-model就可以简单使用
话不多说,直接上代码
<template><el-upload v-model:file-list="fileList" class="upload-demo" action="" :on-preview='openFile' :on-remove="handleRemove":http-request="handleSuccess" :limit="1"><el-button type="primary" :disabled="fileList.length >= 1">选择文件</el-button><template #tip><div class="el-upload__tip"><!-- jpg/png files with a size less than 500kb --></div></template></el-upload>
</template><script lang="ts" setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import type { UploadUserFile } from 'element-plus'
import { uploadAction } from '@/utils/request'
const props = defineProps({modelValue: {type: String,default: ''}
});
const emit = defineEmits(['update:modelValue'])
const downloadUrl = ref('')//回显地址
const fileList = ref<UploadUserFile[]>([// {// name: 'food.jpeg',// url: '',// },
])
// 子组件的方法
function clickSon(val: any) {emit('update:modelValue', val);
}
// 监听 modelValue 的变化
watch(() => props.modelValue, (newVal, ) => {// 可以在这里做一些响应 modelValue 变化的逻辑 //监听父组件传值变化修改listif (newVal) {fileList.value = [{name: newVal,url: downloadUrl.value + newVal}]} else {fileList.value = []}
}, { immediate: true });
const handleRemove = (uploadFile:any, uploadFiles:any) => {// fileList.value = fileList.value.slice(-3)console.log(uploadFile, uploadFiles, '删除了');clickSon('')
}
const handleSuccess = (uploadFile: any, uploadFiles: any) => {console.log(uploadFile, uploadFiles, '上传');if (uploadFile) {let fd = new FormData();fd.append('files', uploadFile.file);console.log(fd, 'fd');//上传文件uploadAction('/api/gpsservice/v1/attachment/multiUpload', fd).then((res: any) => {if (res) {console.log(res[0], 'res');// fileList.value[0].name = res[0].name// fileList.value[0].url = downloadUrl.value + res[0].attachmentPath//上传成功后向父组件传值clickSon( res[0].attachmentPath)}})}
}
//点击预览
const openFile = (e: any) => { // 点击上传的文件列表的文件的操作console.log(e, "点击上传的文件列表的文件的操作");// window.open(e.url);var a = document.createElement("a");console.log(a, "创建a");var event = new MouseEvent("click");a.target = "_blank";a.download = e.name;a.href = e.url;//路径前拼上前缀,完整路径a.dispatchEvent(event);
}</script>
包括预览,删除,里面都实现了