封装element-plus上传图片组件

<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';

模版区使用

<UploadAvatar @getImageUrl="getImageUrl" :imageUrl="table.image" />

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值