【vue2+element-ui】el-upload封装多图上传组件

news/2024/7/10 2:18:46 标签: 前端, elementui, vue

halo小伙伴们,在开发表单中会有遇到需要多图上传,可动态限制上传的图片数量、大小,支持删除、显示提示语的需求。
在这里插入图片描述

在这里插入图片描述
在这小编带来一个小编自封装用了很久的多图上传组件,话不多说上代码。
首先创建一个如:XUploadImgList.vue的文件,编写如下:

<template>
  <div>
    <el-upload
      ref="upload"
      :action="uploadUrl"
      list-type="picture-card"
      :auto-upload="true"
      :headers="headerObj"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-success="successUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :limit="limit"
      accept=".jpg, .jpeg, .png"
    >
      <i slot="default" class="el-icon-plus" />
      <div v-if="showText" slot="tip" class="el-upload__tip">支持上传jpg/png格式图片,单个图片不能超过{{ maxSize }}M,最多上传{{ limit }}张<span v-if="suggestedSize">,建议尺寸: {{ suggestedSize }}</span></div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import api, { getUploadUrlByImage} from "@/api/pagecreator/onlinegrid";

export default {
  name: "XUploadList",
  props:{
    //文件大小限制
    maxSize:{
      default: 2
    },
    //文件数限制
    limit:{
      default: 1
    },
    // 显示提示文本?
    showText:{
      default: true
    },
    value:{
      default: null,
      type:String
    },
    //建议尺寸
    suggestedSize:{
      default:''
    }
  },
  computed:{
    // 获取公共封装的请求地址
    uploadUrl: {
      get() {
        return getUploadUrlByImage()
      }
    }
  },
  data(){
    return{
      dialogImageUrl:'',
      dialogVisible:false,
      fileList: [],
      disabled: false,
      // 设置请求头-看后端需求
      headerObj: {
        Authorization: 'Bearer ' + getToken()
      },
    }
  },
  watch: {
    // 监听初始时图片列表长度, 与limit相等则隐藏按钮
    fileList: {
      handler() {
        this.checkLimit(this.fileList)
        this.fileChange();
      }
    },
    value: {
      deep: true,  // 深度监听
      handler(val) {
        console.log("图片izhi",val)
        if(val){
          if(Array.isArray(val)){
            this.fileList = [];
            // 图片列表回显
            val.forEach((item,index)=>{
              // this.fileList.push({name:item,url:process.env.VUE_APP_API+"/"+item})
              this.fileList.push({name:item,url:item})
            })
          }else {
            this.fileList = [];
            this.fileList.push({name:val,url:val})
          }
        }
      }
    },
  },
  methods: {
    // 检查对比图片数量,对新增按钮进行隐藏
    checkLimit(filelist) {
      const limit = this.limit
      this.$nextTick(()=>{
        const uploadDom = this.$refs['upload']
        if (filelist.length === limit) {
          uploadDom.$children[1].$el.style.display = 'none'
        } else {
          uploadDom.$children[1].$el.style.display = ''
        }
      })
    },
    // 放大查看图片
    handlePictureCardPreview(file){
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 删除图片
    handleRemove(file) {
      // console.log(file)
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid === file.uid) {
          this.fileList.splice(i, 1)
        }
      }
    },
    //监听改变
    fileChange(){
      this.$emit('fileChange',this.fileList)
    },
    //成功上传
    successUpload(response, file, fileList) {
      console.log('执行到这里。。。', response, file, fileList)
      this.fileList.push(file)
    },
    // 选中前钩子
    beforeUpload(file) {
      // console.log("123456",file);
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
	  // 文件类型
      const whiteList = ['jpg', 'jpeg', 'png']
      // 验证格式
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error(file.name + '上传文件只能是 jpg、jpeg、png格式')
        this.$refs.upload.handleRemove(file)
        return false
      }

      const isLt5M = file.size / 1024 / 1024 < this.maxSize
      // 验证大小
      if (!isLt5M) {
        setTimeout(() => {
          this.$message.error(file.name + '上传文件大小不能超过 '+ this.maxSize +'MB')
        }, 10)
        this.$refs.upload.handleRemove(file)
        return false
      }
    },

  }
}
</script>

在需要调用的页面使用如下:

<!--showText:显示文案,value:例如修改页显示图片,max-size:图片最大大小,limit:最多上传数量,fileChange:改变时回调-->
<x-upload-img-list :showText="true" :value="form.imgList" :max-size="5" :limit="6" @fileChange="pictureChange"></x-upload-img-list>

<script>
import XUploadImgList from "@/components/FormField/XUploadImgList";
components: {
  XUploadImgList
},
methods :{
	// 图片上传组件回调--可以操作成自己想要的
	pictureChange(e){
	  console.log('图片上传回调',e)
	  this.form.slideshowList = []
	  e.forEach((item,index)=>{
	    if(item.response){
	      this.form.slideshowList.push(process.env.VUE_APP_API+"/"+item.response.data)
	    }else {
	      this.form.slideshowList.push(item.url)
	    }
	  })
	  this.form.slideshow = this.form.slideshowList.join(','); // 使用逗号将数组转换为字符串
	},
}

</script>

好啦,这是关于一篇vue2的多图上传组件,如果有什么问题及时跟小编联系哦,如果喜欢的话记得给小编三连哈,小伙伴们如果有什么好的组件记得跟小编分享下哦


http://www.niftyadmin.cn/n/5243464.html

相关文章

HarmonyOS4.0从零开始的开发教程08构建列表页面

HarmonyOS&#xff08;六&#xff09;构建列表页面 List组件和Grid组件的使用 简介 在我们常用的手机应用中&#xff0c;经常会见到一些数据列表&#xff0c;如设置页面、通讯录、商品列表等。下图中两个页面都包含列表&#xff0c;“首页”页面中包含两个网格布局&#xff…

postgresql自带指令命令系列二

简介 在安装postgresql数据库的时候会需要设置一个关于postgresql数据库的PATH变量 export PATH/home/postgres/pg/bin:$PATH&#xff0c;该变量会指向postgresql安装路径下的bin目录。这个安装目录和我们在进行编译的时候./configure --prefix [指定安装目录] 中的prefix参…

第三章 核心设计与架构:

核心设计与架构 Kubemetes项目要着重解决的问题&#xff0c;则来自Borg的研究人员在论文中提到的—个非常重要的观点: 在大规模集群中的各种任务之间运行’实际上存在各种各样的关系。这些关系的处理才是作业编排和管理系统最困难的地方。 核心能力与项目定位 Kubemetes项目…

第八章-先进的键盘技巧<The Linux Command Line A Complete Introduction>

一.学习内容 1.我经常开玩笑地把Unix描述为“喜欢打字的人的操作系统”。当然&#xff0c;它甚至有一个命令行就是证明;然而&#xff0c;命令行用户不喜欢输入那么多。 2.否则为什么这么多命令都有这么短的名字&#xff0c;比如cp、ls、mv和rm?事实上&#xff0c;命令行最值…

IntelliJ IDE 插件开发 | (二)UI 界面与数据持久化

系列文章 IntelliJ IDE 插件开发 |&#xff08;一&#xff09;快速入门 前言 在上一篇文章中介绍了在IDEA下开发、运行和安装插件的基本步骤&#xff0c;因此创建项目等基础步骤不再赘述&#xff0c;本文则开始介绍如何进行 UI 界面的开发以及相关数据的持久化存储&#xff…

Notes数据直接在Excel中统计

大家好&#xff0c;才是真的好。 我希望你看过前面两篇内容《Domino REST API安装和运行》和《Domino REST API安装和运行》&#xff0c;因为今天我们正是使用REST API方式在Excel中查询和统计Notes数据。 不过首先你得知道一个OData协议&#xff0c;全名Open Data Protocol(…

Linux系统调试课:I2C tools调试工具

文章目录 一、如何使用I2C tools测试I2C外设1、I2C tools概述: 2、下载I2C tools源码:3、编译I2C tools源码: 4、i2cdetect 5、i2cget 6、i2cdump

流量异常-挂马造成百度收录异常关键词之解决方案(虚拟主机)

一.异常现象&#xff1a;流量突然暴涨&#xff0c;达到平时流量几倍乃至几十倍&#xff0c;大多数情况下因流量超标网站被停止。 二.排查原因&#xff1a; 1.首先分析web日志&#xff1a;访问量明显的成倍、几十倍的增加&#xff1b;访问页面不同&#xff1b;访问IP分散并不固…