Ant Design of Vue中对a-upload组件封装,1.实现上传功能2.实现下载功能3.单个文件上传不能超过1024m4.显示上传的文件列表5.文件列表右侧有删除按钮,可以实现删除功能
时间: 2024-02-01 15:15:03 浏览: 145
可以按照以下步骤进行对a-upload组件的封装:
1. 安装依赖
```
npm install ant-design-vue --save
```
2. 封装上传组件
在Vue组件中引入a-upload,并设置props和methods:
```vue
<template>
<a-upload
:action="uploadUrl"
:before-upload="handleBeforeUpload"
:on-success="handleSuccess"
:on-error="handleError"
:list-type="'text'"
:default-file-list="fileList"
>
<a-button>
<a-icon type="upload"></a-icon>
上传文件
</a-button>
</a-upload>
</template>
<script>
import { Upload, Button, Icon, message } from 'ant-design-vue';
export default {
components: {
'a-upload': Upload,
'a-button': Button,
'a-icon': Icon
},
props: {
uploadUrl: {
type: String,
required: true
},
fileList: {
type: Array,
default: () => []
}
},
methods: {
handleBeforeUpload(file) {
if (file.size > 1024 * 1024 * 1024) {
message.error('文件大小不能超过1024M');
return false;
}
},
handleSuccess(response, file, fileList) {
message.success('文件上传成功');
this.$emit('success', response, file, fileList);
},
handleError(error, response, file) {
message.error('文件上传失败');
this.$emit('error', error, response, file);
}
}
};
</script>
```
其中,props包括上传地址和文件列表,methods包括上传前检查文件大小、上传成功和失败的处理逻辑。
3. 封装下载组件
在Vue组件中引入a标签,设置props和methods:
```vue
<template>
<a :href="downloadUrl" :download="fileName">{{ fileName }}</a>
</template>
<script>
export default {
props: {
downloadUrl: {
type: String,
required: true
},
fileName: {
type: String,
required: true
}
}
};
</script>
```
其中,props包括下载地址和文件名。
4. 文件列表组件
在Vue组件中引入上传和下载组件,同时设置删除按钮的逻辑:
```vue
<template>
<div>
<upload
:uploadUrl="uploadUrl"
:fileList="fileList"
@success="handleUploadSuccess"
@error="handleUploadError"
/>
<div v-for="(file, index) in fileList" :key="index">
<download :downloadUrl="file.downloadUrl" :fileName="file.fileName" />
<a-button icon="delete" @click="handleDeleteFile(index)" />
</div>
</div>
</template>
<script>
import Upload from './Upload';
import Download from './Download';
import { Button } from 'ant-design-vue';
export default {
components: {
Upload,
Download,
'a-button': Button
},
props: {
uploadUrl: {
type: String,
required: true
},
fileList: {
type: Array,
default: () => []
}
},
methods: {
handleUploadSuccess(response, file) {
this.fileList.push({
fileName: file.name,
downloadUrl: response.downloadUrl
});
},
handleUploadError(error) {
console.log(error);
},
handleDeleteFile(index) {
this.fileList.splice(index, 1);
}
}
};
</script>
```
其中,引入了上传和下载组件,并且在删除按钮上绑定了点击事件。
这样,就完成了对a-upload组件的封装,实现了上传、下载和删除功能,并且限制了单个文件大小不能超过1024M。
阅读全文