Vue 59 ,Element 7 ,el-upload 手动上传图片,Vue2 手动上传图片,el-upload上传单张图片,上传后隐藏上传样式

本文分享利用Element Plus的el-upload组件实现图片上传功能,包括限制用户只能上传一次图片,上传成功后隐藏上传按钮。介绍了组件配置、直接使用方法,还提及样式属性和事件函数,旨在为开发者提供实用技巧和示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在上一期中,我们介绍了如何使用 Element Plus 的 el-upload 组件来实现文件上传功能。这里我们分享如何利用 el-upload 组件专门用于图片上传,并实现一些特定的功能需求:限制用户只能上传一次图片,并在成功上传图片后隐藏上传按钮部分。这不仅能够提升用户体验,还能确保数据的一致性和安全性。通过这次分享,希望能为大家提供实用的技巧和示例代码,帮助大家更高效地实现图片上传功能。

一. 实现效果


二. 配置组件

首先,想要在项目中使用 el-upload 组件,得保证项目中已经安装且引入了该组件,具体安装及引入可见上篇文章,请看

el-upload下载使用https://blog.youkuaiyun.com/weixin_65793170/article/details/132627341?spm=1001.2014.3001.5501


三. 直接使用

下载安装,引入注册后,直接在vue组件中使用,请看


<el-upload 
    class="upload_box" 
    ref="upload" 
    :limit="limitNum" 
    :class="{ uploadHide: hideUploadEdit }"                
    :on-change="handleEditChange" 
    :http-request="ImgUploadSectionFile"
    :before-upload="beforeAvatarUpload" 
    :with-credentials="true" 
    :auto-upload="true"
    accept=".png, .jpg" 
    list-type="picture-card" 
    :file-list="fileList"
    action=""
    >
        <!-- 加号标识 -->
        <i slot="default" class="el-icon-plus"></i>
        <!-- 上传后显示 -->
        <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
                <!-- 图片放大 -->
                <span class="el-upload-list__item-preview"                                     
                      @click="handlePictureCardPreview(file)">
                 <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 图片放大 -->
                <span v-if="!disabled" 
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)">
                 <i class="el-icon-delete"></i>
                </span>
            </span>
        </div>
</el-upload>

当然,上传处也可以换成按钮或者其它,像这样,

上传处替换成按钮,代码多去少补,实现代码,请看

<el-upload 
    class="upload_box" 
    ref="upload" 
    :limit="limitNum" 
    :class="{ uploadHide: hideUploadEdit }"                
    :on-change="handleEditChange" 
    :http-request="ImgUploadSectionFile"
    :before-upload="beforeAvatarUpload" 
    :with-credentials="true" 
    :auto-upload="true"
    accept=".png, .jpg" 
    :file-list="fileList"
    :action="uploadImg_url"
    :headers="headers"
    >
        <!-- 上传按钮 -->
        <el-button 
            class="upload_btn" 
            slot="trigger" 
            size="small" 
            type="primary">
            上传图片
            <i class="el-icon-upload el-icon--right"></i>
        </el-button>
        <!-- 上传后显示 -->
        <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
                <!-- 图片放大 -->
                <span class="el-upload-list__item-preview"                                     
                      @click="handlePictureCardPreview(file)">
                 <i class="el-icon-zoom-in"></i>
                </span>
                <!-- 图片放大 -->
                <span v-if="!disabled" 
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)">
                 <i class="el-icon-delete"></i>
                </span>
            </span>
        </div>
</el-upload>

因为这里是本地图片测试上传,所以组件中的action属性为空,上传到接口,还需另行配置。

必要参数:

      // 存储上传的文件列表
      fileList: [],             
      // 诊断图片上传地址
      uploadImg_url: process.env.VUE_APP_BASE_API + "/test/uploads",
      // 上传文件的请求头
      headers: {},


四. 样式属性

相关必要样式和属性介绍,请看

1. 样式

// 隐藏上传按钮
::v-deep .uploadBox_hide .el-upload--picture-card {
    display: none;
}
// 搭配动态 :class 使用
:class="{ uploadBox_hide: hideUploadEdit }" 


这个样式用于,去掉添加/删除文件时的过渡动画
// ::v-deep .el-upload-list__item {
//     transition: none !important;
// }

2. 属性


      :limit="limitNum" //最大允许上传个数
      :class="{hide:hideUploadEdit}" //加类名为了隐藏上传样式
      :on-remove="handleRemove" //文件列表移除文件时的钩子
      :on-change="handleEditChange" //文件状态改变时的钩子(可以限制文件数量和文件大小)
      :http-request="ImgUploadSectionFile" //覆盖默认的上传行为,实现手动上传
      :before-upload="beforeAvatarUpload" //上传文件之前的钩子
      :with-credentials="true" //支持发送 cookie 凭证信息
      :auto-upload="true" //是否在选取文件后立即进行上传(不知什么原因false没效果)
      accept=".png, .jpg" //接受上传的文件类型
      list-type="picture-card" //设置文件列表的样式
      :file-list="fileList" //上传的文件列表
      

      :action="uploadImg_url" // 上传地址   
      :headers="headers" // 地址参数


五. 事件函数

上传图片事件的相关事件函数,请看

import { getToken } from '@/utils/auth'
//在created函数中,先获取请求权限
created() {
    // 想办法获取用户Authorization Bearer
    //const Authorization = store.getters.access_token;
    const Authorization = getToken();
    // console.log(Authorization);

    // 这里配置headers,看接口需不需要加Bearer,一般默认情况是需要加的 
    this.headers = { Authorization: `Bearer ` + Authorization };
    // this.headers = { Authorization: Authorization };
},

事件函数,默认如果配置了:auto-upload="true",选取图片后,会直接调用接口

        // 放大图片
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 删除图片
        handleRemove(file, fileList) {
            if (this.fileList.length === 0) {
                this.fileList = [];
            } else {
                let dl = this.fileList.indexOf(file);
                this.fileList.splice(dl, 1);
            }
            this.hideUploadEdit = this.fileList.length >= this.limitNum;
        },

        // on-change添加文件,上传成功和上传失败时都会被调用
        handleEditChange(file, fileList) {
            this.hideUploadEdit = fileList.length >= this.limitNum;
            // console.log("this.fileList:", this.fileList);
            // console.log("this.hideUploadEdit:", this.hideUploadEdit);
        },

        // http-request自定义上传
        ImgUploadSectionFile(param) {
            this.param = param;
        },

        // before-upload上传文件之前的钩子,参数为上传的文件
        // 若返回 false 或者返回 Promise 且被 reject,则停止上传
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg" || file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },

        // 文件上传成功时的钩子
        handleSuccess(file) {
            // console.log(file);
            const data = file.data;
            //然后数据、逻辑处理
        },

### Vue 中使用 `el-upload` 组件实现单张图片上传 以下是基于 VueElement UI/Plus 的 `el-upload` 组件实现单张图片上传的完整示例代码。此方案适用于 Vue 2Vue 3,并支持图片预览、删除以及隐藏上传按钮等功能。 #### 单张图片上传的核心逻辑 为了实现单张图片上传,需设置 `limit=1` 属性以限制最多只能上传一张图片。同时,在图片上传完成后可以通过监听事件动态调整界面状态,例如隐藏上传按钮或清空文件列表[^2]。 --- ### 示例代码:Vue 3 版本 ```vue <template> <div class="upload-container"> <!-- 图片上传组件 --> <el-upload :action="uploadUrl" list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove" :before-upload="beforeUpload" :on-success="handleSuccess" :limit="1" v-model:file-list="fileList" :class="{ hidden: isHidden }" > <i class="el-icon-plus"></i> </el-upload> <!-- 预览对话框 --> <el-dialog title="图片预览" v-model="dialogVisible"> <img :src="previewImageUrl" alt="Preview Image" style="width: 100%;" /> </el-dialog> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; import type { UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'; // 定义变量 const uploadUrl = 'https://example.com/upload'; // 替换为实际接口地址 const dialogVisible = ref(false); const previewImageUrl = ref(''); const fileList = ref<UploadUserFile[]>([]); const isHidden = ref(false); // 处理图片预览 const handlePreview: UploadProps['onPreview'] = (file) => { previewImageUrl.value = file.url!; dialogVisible.value = true; }; // 删除图片处理 const handleRemove: UploadProps['onRemove'] = () => { fileList.value = []; isHidden.value = false; // 显示上传按钮 }; // 文件上传前校验 const beforeUpload: UploadProps['beforeUpload'] = (rawFile): boolean | void => { if (rawFile.size / 1024 / 1024 > 2) { alert('图片大小不得超过2MB!'); return false; } if (!['image/jpeg', 'image/png'].includes(rawFile.type)) { alert('仅允许上传JPEG/PNG格式的图片!'); return false; } }; // 成功上传后的回调 const handleSuccess: UploadProps['onSuccess'] = () => { isHidden.value = true; // 隐藏上传按钮 }; </script> <style scoped> .hidden { display: none; } ::v-deep .el-upload-list__item { transition: none !important; } </style> ``` --- ### 关键点解析 1. **限制单张图片** 设置属性 `:limit="1"` 可确保用户无法一次性选择多张图片2. **自定义校验规则** 在 `beforeUpload` 方法中对文件类型和大小进行验证,防止不符合条件的文件被上传[^1]。 3. **隐藏上传按钮** 当成功上传图片后,通过绑定类名 `.hidden` 动态控制 `<el-upload>` 是否显示[^4]。 4. **图片预览功能** 利用 `on-preview` 事件触发弹窗展示当前选中的图片[^3]。 5. **删除操作同步更新** 调用 `clearFiles()` 清除内部缓存并重置界面上的状态。 --- ### 示例代码:Vue 2 版本 对于 Vue 2 用户,可参考如下代码: ```vue <template> <div class="upload-container"> <el-upload action="https://example.com/upload" list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove" :before-upload="beforeUpload" :on-success="handleSuccess" :limit="1" v-model:file-list="fileList" :class="{ hidden: isHidden }" > <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img :src="previewImageUrl" alt="Preview Image" style="width: 100%;"> </el-dialog> </div> </template> <script> export default { data() { return { uploadUrl: 'https://example.com/upload', dialogVisible: false, previewImageUrl: '', fileList: [], isHidden: false, }; }, methods: { handlePreview(file) { this.previewImageUrl = file.url; this.dialogVisible = true; }, handleRemove() { this.fileList = []; this.isHidden = false; }, beforeUpload(file) { const isValidType = ['image/jpeg', 'image/png'].includes(file.type); const isValidSize = file.size / 1024 / 1024 < 2; if (!isValidType) { alert('仅允许上传JPEG/PNG格式的图片!'); return false; } if (!isValidSize) { alert('图片大小不得超过2MB!'); return false; } return true; }, handleSuccess() { this.isHidden = true; }, }, }; </script> <style scoped> .hidden { display: none; } ::v-deep .el-upload-list__item { transition: none !important; } </style> ``` --- ### 注意事项 - 如果需要兼容 IE 浏览器,请注意 polyfill 支持。 - 对于 TypeScript 开发者,建议安装对应的类型声明包(如 `@types/element-plus`),以便获得更好的开发体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北城笑笑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值