vue2 upload多图片上传

文章详细描述了如何在Vue应用中使用el-upload组件进行图片上传,包括CSS样式定制以控制显示和隐藏,以及处理文件上传、删除和HTTP请求的方法。

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

dom

   <el-upload
                :class="{ uoloadSty: showBtnImg, disUoloadSty: noneBtnImg }"
                class="avatar-uploader"
                ref="upload" 
                action="#"
                :limit="limitCountImg" //限制上传图片的数量
                :show-file-list="true" //列表展示
                :auto-upload="false" //点击上传
                list-type="picture-card"
                :http-request="handleHttpRequestIcon" //成功
                :on-change="imgChange" //change 
                :on-remove="handleRemove" //删除事件
                accept="image/jpg,image/jpeg,image/png"
              >
                <i class="el-icon-plus"></i>
              </el-upload>

css

::v-deep .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
  background: rgba(255, 255, 255, 0.06);
}
::v-deep .el-upload-list__item-actions {
  width: 100px;
  height: 100px;
}
::v-deep .el-upload-list__item-thumbnail {
  width: 100px;
  height: 100px;
  object-fit: cover;
}
::v-deep .el-upload-list__item {
  width: 100px;
  height: 100px;
  background: rgba(255, 255, 255, 0.06);
}
/* 上传图片时隐藏 */
::v-deep .uoloadSty .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
::v-deep .disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}

script

export default{
data(){
retutn{
      showBtnImg: true,
      noneBtnImg: false,
      limitCountImg: 1,
}

},
methods:{
  imgChange(file, fileList) {
      this.noneBtnImg = fileList.length >= this.limitCountImg;
    },
    // 处理删除事件
    handleRemove(file, fileList) {
      // "文件已被删除:", file
      // "当前文件列表:", fileList
      this.noneBtnImg = !fileList.length <= 0;
    },
    addConfirm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.loadingShow = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          this.$refs.upload.submit();
        }
      });
    },
    handleHttpRequestIcon(file) {
      httpIconRequest(file, {
        next: (response) => {
          // console.log(response);
        },
        error: (err) => {
          this.loadingShow.close();
        },
        complete: (res) => {
          this.loadingShow.close();
          this.room.room_avatar = res.key;
        },
      });
    },
}


}

### Vue 中使用 `el-upload` 组件实现单张图片上传 以下是基于 Vue 和 Element 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值