封装element-plus上传图片组件

2023-12-30 10:33:12
<template>
    <el-upload v-model:file-list="upload.fileList" :action="upload.action" list-type="picture-card"
        :before-upload="upload.before" :on-success="upload.success" limit :on-preview="upload.proview"
        :data-fileListCount="upload.fileList.length" :name="upload.name" :on-remove="upload.remove">
        <el-icon>
            <Plus />
        </el-icon>
    </el-upload>
 
    <el-dialog v-model="upload.dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false"
        append-to-body>
        <img w-full :src="upload.dialogImageUrl" alt="" style="width:100%;height:100%" />
    </el-dialog>
</template>
 
<script setup>
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import baseUrl from '@/api/baseUrl.js'
const props = defineProps({
    imageUrl: String,
});
const emit = defineEmits(['getImageUrl'])
const upload = reactive({
    name: 'file',
    action: '接口地址',
    fileList: props.imageUrl ? [{ url: props.imageUrl }] : [],
    dialogImageUrl: '',
    dialogVisible: false,
    before: (file) => {
        const type = ['image/png', 'image/jpeg', 'image/gif'];
        if (!type.includes(file.type)) {
            ElMessage.error('不支持该类型文件')
            return false
        }
    },
    proview: ({ url }) => {
        console.log(url);
        upload.dialogImageUrl = url;
        upload.dialogVisible = true;
    },
    success: (res, uploadFile, uploadFiles) => {
        console.log(res);
        console.log(uploadFile);
        if (res.url && res.code === 1) {
            upload.fileList = [{
                url: uploadFile.url,
            }];
            emit('getImageUrl', res.url, uploadFile.url);
            // document.querySelector('.el-upload--picture-card').style.display = "none"
        } else {
            ElMessage({ type: 'warning', message: res.msg });
            upload.fileList = [];
            emit('getImageUrl', '', '');
        }
    },
    remove: (file, files) => {
        upload.fileList = [];
        emit('getImageUrl', '', '');
    }
})
</script>
<style scope lang="scss">
[data-fileListCount='1'] {
    .el-upload--picture-card {
        display: none !important;
    }
}
</style>

页面使用:

import UploadAvatar from '@/components/UploadAvatar/index.vue';

模版区

import UploadAvatar from '@/components/UploadAvatar/index.vue';

文章来源:https://blog.csdn.net/m0_74801194/article/details/135283883
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。