Ant Design of Vue中对a-upload组件封装,1.实现上传功能2.实现下载功能3.单个文件上传不能超过1024m4.文件列表右侧有删除按钮,可以实现删除功能6.用ts语法实现前面功能
时间: 2024-02-01 10:15:30 浏览: 83
以下是基于 TypeScript 的 Ant Design of Vue 对 a-upload 组件的封装,实现上传、下载和删除功能,同时限制单个文件上传大小不超过1024MB,文件列表右侧有删除按钮:
```typescript
<template>
<div>
<a-upload
:before-upload="beforeUpload"
:file-list="fileList"
:show-upload-list="false"
@change="handleUpload">
<a-button type="primary">上传文件</a-button>
</a-upload>
<a-table :columns="columns" :dataSource="dataSource"></a-table>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Upload, Button, Table, Popconfirm } from 'ant-design-vue';
import { UploadFile } from 'ant-design-vue/types/upload';
import { ColumnProps } from 'ant-design-vue/types/table/column';
export default defineComponent({
name: 'MyUpload',
components: {
'a-upload': Upload,
'a-button': Button,
'a-table': Table,
'a-popconfirm': Popconfirm,
},
data() {
return {
fileList: [] as UploadFile[],
dataSource: [] as UploadFile[],
};
},
computed: {
columns(): ColumnProps[] {
return [
{
title: '文件名',
dataIndex: 'name',
},
{
title: '操作',
dataIndex: 'action',
customRender: ({ file }: { file: UploadFile }) => (
<a-popconfirm
title="确定删除该文件吗?"
onConfirm={() => this.handleDelete(file)}
>
<a-button type="danger" size="small">
删除
</a-button>
</a-popconfirm>
),
},
];
},
},
methods: {
beforeUpload(file: UploadFile) {
const isLt1024M = file.size / 1024 / 1024 < 1024;
if (!isLt1024M) {
this.$message.error('上传文件大小不能超过1024MB');
}
return isLt1024M;
},
handleUpload({ fileList }: { fileList: UploadFile[] }) {
this.fileList = fileList;
this.dataSource = fileList;
},
handleDelete(file: UploadFile) {
this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
this.dataSource = this.dataSource.filter(
(item) => item.uid !== file.uid,
);
},
},
});
</script>
```
在上述代码中,我们使用 `a-upload` 组件实现文件上传功能,并通过 `before-upload` 属性限制单个文件上传大小不超过1024MB。上传成功后,我们将上传的文件列表赋值给 `fileList` 和 `dataSource` 变量,并在表格中展示出来。表格中的“操作”列包含一个删除按钮,点击该按钮会触发 `handleDelete` 方法,并将对应的文件从列表中删除。同时,我们使用 TypeScript 的类型定义来规范代码,提高开发效率和代码质量。
阅读全文