Vue3 + ant-design-vue@3.2.15 + UploadPictureCard

<template>
    <a-upload
        name="file"
        v-model:file-list="showFileList"
        list-type="picture-card"
        :multiple="multiple"
        :max-count="maxCount"
        :before-upload="beforeUpload"
        :accept="accept"
        @remove="handleRemove"
    >
        <div v-if="maxCount === null || showFileList.length < maxCount">
            <plus-outlined />
            <div style="margin-top: 8px">{{ text }}</div>
        </div>
    </a-upload>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { UploadProps } from 'ant-design-vue';
import { apiUploadFiles } from '@/request/api/common';
const props = defineProps({
    text: {
        type: String,
        default: '上传图片',
    },
    multiple: {
        type: Boolean,
        default: false,
    },
    maxCount: {
        type: Number,
        default: null,
    },
    file_key: {
        type: String,
        default: 'img',
    },
    data_list: {
        type: Array,
        default: () => [],
    },
    accept: {
        type: String,
        default: 'image/*',
    },
});
// 保留当前的文件列表
const file_list = ref([]);
// 上传
const beforeUpload = async (file: File) => {
    const _data: API.IUploadParams = {
        files: file,
        type: 'image',
    };
    const _res = await apiUploadFiles(_data);
    if (_res.code == 200) {
        file_list.value.push(_res.data[0]);
        emit('UpdateUploadFile', props.file_key, file_list.value);
    }
    return false;
};
// 移除
const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = file_list.value.indexOf(file);
    const newFileList = file_list.value.slice();
    newFileList.splice(index, 1);
    file_list.value = newFileList;
    emit('UpdateUploadFile', props.file_key, file_list.value);
};

const emit = defineEmits(['UpdateUploadFile']);
// 定义文件上传列表
let showFileList = ref([]);
// 设置默认值
const setDefaultData = () => {
    if (props.data_list && props.data_list.length) {
        showFileList.value = props.data_list.map((item) => {
            return { url: item };
        });
        file_list.value = props.data_list;
    } else {
        showFileList.value = [];
        file_list.value = [];
    }
};
onMounted(() => {
    setDefaultData();
});
</script>

<style lang="scss" scoped></style>

 

posted @ 2023-11-28 10:41  riven.lcs  阅读(72)  评论(0编辑  收藏  举报