在弹窗里面用ant design vue 具体写一个上传文件,文件可以预览与下载,并且可以回显的vue,在提交的时候可以获取到值
时间: 2023-05-24 17:05:08 浏览: 392
<template>
<div>
<a-modal v-model="visible" :title="title" :width="width" :cancel-text="cancelText" :ok-text="okText" @ok="handleOk">
<a-form :form="form" ref="form">
<a-form-item label="上传文件" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-upload
ref="upload"
:accept="accept"
:max-size="maxSize"
:before-upload="beforeUpload"
:show-upload-list="showUploadList"
:multiple="multiple"
@change="handleChange"
>
<a-button :disabled="uploadDisabled">
<a-icon type="upload" /> 点击上传
</a-button>
</a-upload>
<div v-if="!_.isEmpty(fileList)">
<div v-for="(file, index) in fileList" :key="index">
<a-tooltip :title="file.name">
<span>{{ file.name }}</span>
</a-tooltip>
<a-tooltip title="下载文件">
<a-icon type="download" :href="file.url" target="_blank" />
</a-tooltip>
<a-tooltip title="预览文件">
<a-icon type="eye" @click="previewFile(file)" />
</a-tooltip>
</div>
</div>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script>
import { Modal, Form, Input, Button, Upload, Tooltip, Icon } from 'ant-design-vue';
import _ from 'lodash';
export default {
components: {
'a-modal': Modal,
'a-form': Form,
'a-form-item': Form.Item,
'a-input': Input,
'a-button': Button,
'a-upload': Upload,
'a-tooltip': Tooltip,
'a-icon': Icon,
},
props: {
value: {
type: Object,
required: true,
default: () => ({
fileList: [],
}),
},
title: {
type: String,
required: true,
},
width: {
type: Number,
default: 520,
},
cancelText: {
type: String,
default: '取消',
},
okText: {
type: String,
default: '确定',
},
accept: {
type: String,
default: '',
},
maxSize: {
type: Number,
default: 1024 * 1024 * 10, // 10M
},
showUploadList: {
type: Boolean,
default: true,
},
multiple: {
type: Boolean,
default: false,
},
},
data() {
return {
form: {},
visible: false,
fileList: [],
uploadDisabled: false,
};
},
watch: {
value: {
handler(val) {
this.fileList = val.fileList || [];
},
immediate: true,
},
},
methods: {
beforeUpload(file) {
if (file.size > this.maxSize) {
this.$message.error(`文件大小不能超过 ${this.maxSize / 1024 / 1024}MB`);
return false;
}
return true;
},
handleChange({ file, fileList }) {
if (file.status === 'uploading') {
this.uploadDisabled = true;
}
if (file.status === 'done') {
this.uploadDisabled = false;
}
this.fileList = fileList.map(item => ({
uid: item.uid,
name: item.name,
url: item.response?.url,
}));
},
previewFile(file) {
const ext = file.name.split('.').pop().toLowerCase();
if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
this.$preview({
img: file.url,
title: file.name,
});
} else if (['pdf', 'doc', 'docx', 'xls', 'xlsx'].includes(ext)) {
window.open(file.url, '_blank');
} else {
this.$message.error('暂不支持该文件预览!');
}
},
handleOk() {
this.$emit('input', { fileList: this.fileList });
this.$emit('ok');
},
},
};
</script>
阅读全文