【sgUploadImage】自定义组件:基于elementUI的el-upload封装的上传图片、相片组件,适用于上传缩略图、文章封面

news2025/4/7 10:27:15

sgUploadImage源码

<template>
  <div :class="$options.name">
    <ul class="uploadImages">
      <li
        class="uploadImage"
        v-loading="loadings[i]"
        v-for="(a, i) in uploadImages"
        :key="i"
        @click="clickFile(a)"
      >
        <img :src="a" @load="load(a, i)" v-if="typeof a !== 'number'" />
        <el-button
          v-if="showRemoveBtn(a)"
          class="remove-btn"
          type="text"
          icon="el-icon-delete"
          @click.stop="remove(a, i)"
        />
      </li>
    </ul>
    <el-alert
      v-if="alertMsg !== false"
      style="margin-top: 10px"
      :closable="true"
      :close-text="``"
      :description="``"
      :effect="'light'"
      :show-icon="true"
      :title="alertMsg || `最多可上传${limit}个图片,每个附件大小不超过${maxSize}M`"
      :type="'warning'"
    />
    <el-upload
      style="display: none"
      ref="upload"
      :accept="accept"
      :action="'#'"
      :auto-upload="false"
      :multiple="true"
      :on-change="change"
      :show-file-list="false"
    />
    <el-image ref="image" style="display: none" src="" :preview-src-list="[previewSrc]" />
  </div>
</template>
<script>
export default {
  name: "sgUploadImage",
  components: {},
  data() {
    return {
      accept: `.${this.$global.resourceTypes
        .find((v) => v.label == `图片`)
        .suffixs.join(",.")}`,
      form: {},
      uploadBtn: null, //上传触发按钮
      disabled: false,
      alertMsg: ``, //如果为false就隐藏提示内容
      limit: 1, //默认只能传1张
      maxSize: 10, //默认最大传10MB的图片
      imgFiles: [], //图像的base64对象数组
      files: [], //图像的File对象数组
      previewSrc: null,
      loadings: [],
    };
  },
  props: ["data"],
  computed: {
    uploadImages() {
      return this.imgFiles && this.imgFiles.length ? this.imgFiles : 1;
    },
  },
  watch: {
    data: {
      handler(newValue, oldValue) {
        //console.log(`深度监听${this.$options.name}:`, newValue, oldValue);
        if (Object.keys(newValue || {}).length) {
          this.form = JSON.parse(JSON.stringify(newValue));
        } else {
          this.form = {};
        }
        this.disabled = this.form.disabled;
        this.alertMsg = this.form.alertMsg;
        // 获取外部回显上传列表----------------------------------------
        let files =
          typeof this.form.files === `string`
            ? JSON.parse(this.form.files || "[]")
            : this.form.files || [];
        Array.isArray(files) || (files = [files]);
        this.files = files;
        this.imgFiles = [];
        this.files.forEach((v, i) => this.getImageSrc(v, i));
        // ----------------------------------------
        this.form.accept && (this.accept = this.form.accept);
        this.form.limit && (this.limit = this.form.limit);
        this.form.maxSize && (this.maxSize = this.form.maxSize);
        this.$nextTick(() => {
          let width = this.form.width || 200;
          let height = this.form.height || 150;
          this.$el.style.setProperty("--uploadImage_width", `${width}px`);
          this.$el.style.setProperty("--uploadImage_height", `${height}px`);
          this.$el.style.setProperty(
            "--background",
            `url(http://via.placeholder.com/${width}x${height})`
          );
          this.uploadBtn = this.$refs.upload.$children[0].$refs.input;
          this.uploadBtn.webkitdirectory = this.form.webkitdirectory; //让el-upload支持上传文件夹
        });
      },
      deep: true, //深度监听
      immediate: true, //立即执行
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    load(d, idx) {
      this.$set(this.loadings, idx, false);
    },
    getImageSrc(file, idx = this.files.length - 1) {
      this.$set(this.loadings, idx, true);
      if (file.path) {
        this.imgFiles.push(this.$d.responseFile(file));
      } else {
        this.$g.file2Base64Image(file, (d) => this.imgFiles.push(d));
      }
    },
    showRemoveBtn(d) {
      return !(typeof d === "number");
    },
    remove(d, i) {
      this.files.splice(i, 1);
      this.imgFiles.splice(i, 1);
      this.$emit(`change`, { files: this.files });
    },

    showImage(previewSrc) {
      this.previewSrc = previewSrc;
      this.$refs.image.showViewer = true; //显示大图
    },
    clickFile(d) {
      if (this.disabled) return;
      if (typeof d === "number") {
        this.uploadBtn.click();
      } else {
        this.showImage(d);
      }
    },
    change(file) {
      if (this.files.length >= this.limit) {
        this.$message(`最多只能上传${this.limit}个文件`);
      } else {
        let fileSizeMB = file.size / 1024 / 1024; //转换文件大小(单位MB)
        if (this.maxSize && fileSizeMB > this.maxSize) {
          this.$message(
            `“${file.name}”文件大小超过${this.$g.getSize(this.maxSize * 1024 * 1024)}`
          );
        } else {
          this.files.push(file.raw);
          this.getImageSrc(file.raw);
          this.$emit(`change`, { files: this.files });
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.sgUploadImage {
  .uploadImages {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .uploadImage {
      flex-shrink: 0;
      margin-right: 10px;
      margin-bottom: 10px;
      position: relative;
      border-radius: 4px;
      width: var(--uploadImage_width);
      height: var(--uploadImage_height);
      /*背景图片*/
      background: #f5f7fa var(--background) no-repeat center / cover;
      img {
        width: 100%;
        height: 100%;
        object-position: center;
        object-fit: cover;
      }
      &:last-of-type {
        margin-bottom: 0;
      }
      &:hover {
        .remove-btn {
          opacity: 1;
          pointer-events: auto;
        }
      }
      .remove-btn {
        background-color: #f56c6c;
        border-radius: 88px;
        box-sizing: border-box;
        padding: 5px;
        color: white;
        cursor: pointer;
        transition: 0.2s;
        position: absolute;
        right: 10px;
        top: 10px;
        opacity: 0;
        pointer-events: none;
        &:hover {
          background-color: red;
        }
      }
    }
  }
}
</style>

应用

<sgUploadImage @change="getUploadFiles" />


...


getUploadFiles({ files }) {
    console.log(`获取上传文件:`, files);
},

基于基础的el-upload组件使用【实用的代码片段】基于elementUI的el-upload的上传文件对象获取代码片段,支持上传单个、多个File或文件夹(可以获取文件夹下钻子文件夹递归文件)-CSDN博客文章浏览阅读133次,点赞5次,收藏2次。文章浏览阅读192次。【代码】【sgUploadList】自定义组件:基于elementUI的el-upload封装的上传列表组件,适用于上传附件时。【sgUploadList】自定义组件:基于elementUI的el-upload封装的上传列表组件,适用于上传附件时-CSDN博客。https://blog.csdn.net/qq_37860634/article/details/144338242

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2257704.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【重生之我在B站学MySQL】

MySQL笔记 文章目录 MySQL的三层结构SQL语句分类sql语句数据库操作创建数据库查看、删除数据库 表操作创建表mysql常用数据类型(列类型)查询表、插入值创建表练习创建一个员工表emp 修改表mysql约束primary key(主键)not null(非空)unique(唯一)foreign key(外键)check自增长 索…

Java版企业电子招标采购系统源业码Spring Cloud + Spring Boot +二次开发+ MybatisPlus + Redis

功能描述 1、门户管理&#xff1a;所有用户可在门户页面查看所有的公告信息及相关的通知信息。主要板块包含&#xff1a;招标公告、非招标公告、系统通知、政策法规。 2、立项管理&#xff1a;企业用户可对需要采购的项目进行立项申请&#xff0c;并提交审批&#xff0c;查看所…

eclipse启动的时候,之前一切很正常,但突然报Reason: Failed to determine a suitable driver class的解决

1、之前项目都是启动正常的&#xff0c;然后运行以后发现启动不了了&#xff0c;还会报错&#xff1a; 2、这个Reason: Failed to determine a suitable driver class&#xff0c;说是没有合适的驱动class spring:datasource:url: jdbc:sqlserver://192.168.1.101:1433;databa…

PostGIS分区表学习相关

在Postgresql中对空间数据进行表分区的实践_postgresql空间数据-CSDN博客文章浏览阅读1.4k次&#xff0c;点赞26次&#xff0c;收藏21次。Postgresql的分区功能允许将一个大表按照特定的规则拆分成多个小的分区表。这样做的好处在于&#xff0c;在查询数据时&#xff0c;可以只…

【sgUploadList】自定义组件:基于elementUI的el-upload封装的上传列表组件,适用于上传附件时

sgUploadList源码 <template><div :class"$options.name"><ul class"files"><li v-for"(a, i) in files" :key"i"><sgFileLink :data"a" remove"remove(a, i)" clearable /></…

C#核心(16)万物之父和装箱拆箱

前言 西方说人类的万物之父是亚当&#xff0c;中国说人类的万物之母是女娲&#xff0c;那么c#中有没有一个万物之父呢&#xff1f; 有&#xff0c;我们今天就来浅浅聊一下。 在C#和许多其他面向对象编程语言中&#xff0c;“万物之父”指的是Object类。这个类的历史和重要性…

网页核心页面设计(第7章)

一、生态家居网页 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta http-equiv"X-UA-Compatible" content"IEedge" /><meta name"viewport" content"widthdevi…

IoTDB 删除数据后文件大小不减反增

现象 时序数据库 IoTDB 删除大量数据后&#xff0c;为什么 data 空间不减反增&#xff1f; 原因 IoTDB 的存储引擎采用 LSM&#xff08;Log-Structured Merge&#xff09;架构。在执行删除操作时&#xff0c;系统会生成 .mod 文件来标记删除的数据。这些删除标记会在后续的合…

WPF Prism 01-BootstrapperShell

Prism介绍 Prism 是一个用于在 WPF、.NET MAUI、Uno 平台和 Xamarin Forms 中构建松耦合、可维护和可测试的 XAML 应用程序的框架。每个平台都有单独的发布版本&#xff0c;并且这些版本将在独立的开发时间线上进行开发。Prism 提供了一组设计模式的实现&#xff0c;这些模式有…

html中,实现通过拖拽调整图像尺寸

<!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta name"viewport" content"widthdevice-width, initial-scale1.0"> <title>html中拖拽修改图像尺寸</title> <styl…

Composer在安装的过程中经常找不到刚更新的包

明明有v2.1.0版本&#xff0c;安装就是找不到这个版本的包。 1. Composer 官方网址&#xff1a;https://getcomposer.org 中文网站&#xff1a;https://www.phpcomposer.com 官方文档&#xff1a;https://docs.phpcomposer.com 2. Packagist Packagist 是 Composer的组件仓库…

项目实例_FashionMNIST_CNN

前言 提醒&#xff1a; 文章内容为方便作者自己后日复习与查阅而进行的书写与发布&#xff0c;其中引用内容都会使用链接表明出处&#xff08;如有侵权问题&#xff0c;请及时联系&#xff09;。 其中内容多为一次书写&#xff0c;缺少检查与订正&#xff0c;如有问题或其他拓展…

使用数据库同步中间件DBSyncer实现不同数据库的数据同步

点击上方蓝字关注我 有去O(ORACLE数据库)、信创、国产化数据库等项目实践的同学应该都遇到过不同数据库之前进行数据迁移的问题&#xff0c;虽然有各种工具可以实现&#xff0c;但是有些工具的部署、使用比较复杂&#xff0c;也有些工具迁移数据效率很低。本文将介绍一款开源且…

SQL汇总数据:聚集函数

我们经常需要汇总数据而无需实际检索出这些数据&#xff0c;为此SQL提供了专门的函数。使用这些函数&#xff0c;SQL查询能够高效地检索数据&#xff0c;以便进行分析和报表生成。这类检索的例子包括&#xff1a; 确定表中行数&#xff08;或者满足某个条件或包含某个特定值的…

HTML颜色-HTML脚本

HTML脚本 js使得HTML页面具有更强的动态和交互性 HTML<script>标签 标签用于定义客户端脚本&#xff0c;比如javascript 可包含脚本语句&#xff0c;也可以通过src属性指向外部的脚本文件 JavaScript最常用于图片操作&#xff0c;表单验证以及动态的内容更新 HTML<n…

ASP.NET Core8.0学习笔记(二十五)——EF Core Include导航数据加载之预加载与过滤

一、导航属性数据加载 1.在EF Core中可以使用导航属性来加载相关实体。 2.加载实体的三种方式&#xff1a; (1)预先加载&#xff1a;直接在查询主体时就把对应的依赖实体查出来&#xff08;作为初始查询的一部分&#xff09; (2)显式加载&#xff1a;使用代码指示稍后显式的从…

【工具变量】上市公司企业过度负债数据(2000-2022年)

一、计算方式&#xff1a;参考C刊《投资研究》汪昌云&#xff08;2022&#xff09;老师的研究&#xff0c;将实际负债率与 Tobit 回归得到的目标负债率之差认定为过度负债率&#xff0c;该种方式认为目标负债率的驱动因素包括公司特征与行业因素&#xff0c;较为全面&#xff0…

分布式数据库中间件-Sharding-JDBC

文章目录 Sharding-JDBCSharding-JDBC介绍Sharding-JDBC的作用什么是分库分表分库分表的方式分库分表带来的问题事务一致性问题跨节点关联查询跨节点分页、排序函数主键重复 Sharding-JDBC 入门&#xff08;水平分表&#xff09;需求说明环境搭建编写代码流程分析其他配置方式概…

FPGA 16 ,Verilog中的位宽:深入理解与应用

目录 前言 一. 位宽的基本概念 二. 位宽的定义方法 1. 使用向量变量定义位宽 ① 向量类型及位宽指定 ② 位宽范围及位索引含义 ③ 存储数据与字节数据 2. 使用常量参数定义位宽 3. 使用宏定义位宽 4. 使用[:][-:]操作符定义位宽 1. 详细解释 : 操作符 -: 操作符 …

HTML:表格重点

用表格就用table caption为该表上部信息&#xff0c;用来说明表的作用 thead为表头主要信息&#xff0c;效果加粗 tbody为表格中的主体内容 tr是 table row 表格的行 td是table data th是table heading表格标题 &#xff0c;一般表格第一行的数据都是table heading