乘风原创程序

  • 利用Vue3和element-plus实现图片上传组件
  • 2022/3/15 14:10:48
  • 前言

    element-plus 提供了 uploader 组件,但是不好定制化,所以自己又造了个轮子,实现了一个图片上传的组件,它的预期行为是:

    1.还没上传图片时,显示上传卡片

    2.上传图片时显示进度条,隐藏上传卡片

    3.上传成功时显示图片缩略图,上传失败则显示失败提示

    4.支持上传图片的预览和删除

    具体如下图所示:

    具体代码

    图片上传

    这里使用的图床是牛图网,无需注册,貌似也没有图片大小的限制,但是请不要上传违规图像。

    <code>import axios from "axios"
    import { elmessage } from 'element-plus'
    
    
    const service = axios.create({
        baseurl: "/image"
    })
    
    service.interceptors.response.use(response => {
        const code = response.data.code || 200
        if (code === 200) {
            return response.data.data
        }
    
        let msg = response.data.code + " " + response.data.msg
        elmessage.error(msg)
    
        return promise.reject('上传图片失败:' + msg)
    })
    
    /**
     * 上传图片
     * @param {file} file 图片文件
     * @param {refimpl} progress 上传进度
     * @returns promise
     */
    function uploadimage(file, progress) {
        let formdata = new formdata();
        formdata.append("file", file)
        return service({
            url: "/upload",
            method: "post",
            data: formdata,
            onuploadprogress(event) {
                let v = math.round(event.loaded / event.total * 100)
                progress.value = v == 100 ? 80 : v
            },
    
        })
    }
    
    export { uploadimage }
    

    这里使用 onuploadprogress 来监视上传进度,但是实际上直接使用计算出来的进度往往会和实际的存在很大的偏差,也就是说:即使你还在上传,axios 也会告诉你已经上传完了,所以这里把 100 的进度换成了 80,真正的 100 进度应该在服务器返回 url 时设置。

    受到同源策略的限制,我们需要在 vue.config.js 中配置一下代理服务器:

    <code>module.exports = {
        devserver: {
            proxy: {
                "/image": {
                    target: "https://niupic.com/api",
                    pathrewrite: { "^/image": "" },
                },
            }
        }
    }
    

    上传组件

    图片预览功能用的是 vue-easy-light-box,如果没有安装的话可以 npm install --save vue-easy-lightbox@next 安装一下。下面是具体代码:

    <code><template>
        <div class="uploader">
            <input
                type="file"
                id="file-input"
                style="display: none"
                accept="image/*"
                @change="onimageadded"
            />
    
            <div
                class="card upload-card"
                @click="openfiledialog"
                v-if="!isthumbnailvisible"
            >
                <svg
                    class="icon"
                    width="28"
                    height="28"
                    viewbox="0 0 1024 1024"
                    xmlns="http://www.w3.org/2000/svg"
                >
                    <path
                        fill="#8c939d"
                        d="m480 480v128a32 32 0 0164 0v352h352a32 32 0 110 64h544v352a32 32 0 11-64 0v544h128a32 32 0 010-64h352z"
                    ></path>
                </svg>
            </div>
    
            <div class="card thumbnail-card" v-show="isthumbnailvisible">
                <img src="" alt="缩略图" id="thumbnail" />
    
                <label class="success-label" v-show="issuccesslabelvisible"
                    ><i class="success-icon"
                        ><svg
                            class="icon"
                            width="12"
                            height="12"
                            viewbox="0 0 1024 1024"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <path
                                fill="white"
                                d="m406.656 706.944l195.84 496.256a32 32 0 10-45.248 45.248l256 256 512-512a32 32 0 00-45.248-45.248l406.592 706.944z"
                            ></path></svg
                    ></i>
                </label>
    
                <!-- 图标 -->
                <div class="thumbnail-actions">
                    <span class="thumbnail-preview" @click="handlethumbnailpreview">
                        <svg
                            class="icon"
                            width="20"
                            height="20"
                            viewbox="0 0 1024 1024"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <path
                                fill="white"
                                d="m795.904 750.72l124.992 124.928a32 32 0 01-45.248 45.248l750.656 795.904a416 416 0 1145.248-45.248zm480 832a352 352 0 100-704 352 352 0 000 704zm-32-384v-96a32 32 0 0164 0v96h96a32 32 0 010 64h-96v96a32 32 0 01-64 0v-96h-96a32 32 0 010-64h96z"
                            ></path>
                        </svg>
                    </span>
    
                    <span class="thumbnail-delete" @click="handlethumbnailremove">
                        <svg
                            class="icon"
                            width="20"
                            height="20"
                            viewbox="0 0 1024 1024"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <path
                                fill="white"
                                d="m160 256h96a32 32 0 010-64h256v95.936a32 32 0 0132-32h256a32 32 0 0132 32v192h256a32 32 0 110 64h-64v672a32 32 0 01-32 32h192a32 32 0 01-32-32v256zm448-64v-64h416v64h192zm224 896h576v256h224v640zm192-128a32 32 0 01-32-32v416a32 32 0 0164 0v320a32 32 0 01-32 32zm192 0a32 32 0 01-32-32v416a32 32 0 0164 0v320a32 32 0 01-32 32z"
                            ></path>
                        </svg>
                    </span>
                </div>
    
                <!-- 进度条 -->
                <el-progress
                    type="circle"
                    :percentage="progress"
                    v-show="isprogressvisible"
                    :width="110"
                    id="progress"
                />
            </div>
    
            <vue-easy-lightbox
                movedisabled
                :visible="islightboxvisible"
                :imgs="localimageurl"
                :index="index"
                @hide="handlelightboxhide"
            />
        </div>
    </template>
    
    <script>
    import { ref, computed } from "vue";
    import { uploadimage } from "../api/image";
    import { plus } from "@element-plus/icons-vue";
    import vueeasylightbox from "vue-easy-lightbox";
    import { elmessage } from 'element-plus/lib/components';
    
    export default {
        name: "kilakilauploader",
        emits: ["uploaded", "abouttoupload", "removed"],
        components: { plus, vueeasylightbox },
        setup(props, context) {
            let progress = ref(0);
            let islightboxvisible = ref(false);
            let isprogressvisible = ref(false);
            let issuccesslabelvisible = ref(false);
            let imageurl = ref("");
            let localimageurl = ref("");
            let index = ref(0);
    
            let isthumbnailvisible = computed(() => localimageurl.value.length > 0);
    
            function openfiledialog() {
                document.getelementbyid("file-input").click();
            }
    
            function onimageadded() {
                let fileinput = document.getelementbyid("file-input");
                if (fileinput.files.length == 0) {
                    return;
                }
    
                context.emit("abouttoupload");
                let file = fileinput.files[0];
                setimageurl(url.createobjecturl(file));
                upload(file);
            }
    
            function setimageurl(url) {
                let thumbnailel = document.getelementbyid("thumbnail");
                thumbnailel.src = localimageurl.value = url;
            }
    
            function handlethumbnailremove(file) {
                imageurl.value = "";
                localimageurl.value = "";
                context.emit("removed", file);
            }
    
            function handlethumbnailpreview() {
                islightboxvisible.value = true;
            }
    
            function handlelightboxhide() {
                islightboxvisible.value = false;
            }
    
            function upload(file) {
                progress.value = 0;
                isprogressvisible.value = true;
                issuccesslabelvisible.value = false;
    
                uploadimage(file, progress).then(
                    (url) => {
                        progress.value = 100;
                        imageurl.value = url;
                        document.getelementbyid("thumbnail").src = url;
                        context.emit("uploaded", url);
    
                        settimeout(() => {
                            isprogressvisible.value = false;
                            issuccesslabelvisible.value = true;
                        }, 200);
                    },
                    () => {
                        isprogressvisible.value = false;
                        localimageurl.value = "";
                        context.emit("uploaded", "");
                        elmessage.error("哎呀,图片上传出错啦~")
                    }
                );
            }
    
            return {
                progress,
                imageurl,
                localimageurl,
                index,
                islightboxvisible,
                isthumbnailvisible,
                isprogressvisible,
                issuccesslabelvisible,
                handlethumbnailremove,
                handlethumbnailpreview,
                handlelightboxhide,
                openfiledialog,
                onimageadded,
                setimageurl,
            };
        },
    };
    </script>
    
    <style lang="less" scoped>
    .uploader {
        display: flex;
    }
    
    .card {
        background-color: #fbfdff;
        border: 1px dashed #c0ccda;
        border-radius: 6px;
        width: 148px;
        height: 148px;
        overflow: hidden;
    }
    
    .upload-card {
        display: flex;
        justify-content: center;
        align-items: center;
        transition: all 0.3s;
        cursor: pointer;
    
        &:hover {
            border-color: #409eff;
            color: #409eff;
        }
    }
    
    .thumbnail-card {
        border: 1px solid #c0ccda;
        position: relative;
    
        #thumbnail {
            width: 100%;
            height: 100%;
            object-fit: contain;
            display: inline;
        }
    
        .success-label {
            position: absolute;
            right: -15px;
            top: -6px;
            width: 40px;
            height: 24px;
            background: #67c23a;
            text-align: center;
            transform: rotate(45deg);
            box-shadow: 0 0 1pc 1px #0003;
    
            .success-icon {
                position: absolute;
                left: 13px;
                top: 1px;
                transform: rotate(-45deg);
            }
        }
    
        #progress {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            background: rgba(255, 255, 255, 0.7);
    
            :deep(.el-progress-circle) {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    
        .thumbnail-actions {
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            opacity: 0;
            transition: all 0.4s ease;
            display: flex;
            justify-content: center;
            align-items: center;
            position: absolute;
            top: 0;
            left: 0;
            border-radius: 6px;
    
            .thumbnail-preview,
            .thumbnail-delete {
                cursor: pointer;
                margin: 0 8px;
                display: inline-block;
            }
    
            &:hover {
                opacity: 1;
            }
        }
    }
    
    :deep(.vel-img) {
        box-shadow: 0 5px 20px 2px rgba(0, 0, 0, 0.35);
    }
    </style>
    

    在图片上传之前、上传完成和移除图片的时候都会触发相应的自定义事件,父级组件可以处理这些事件来设置图片 url。

    以上就是利用vue3和element-plus实现图片上传组件的详细内容,更多关于vue3 element-plus图片上传的资料请关注本教程网其它相关文章!