element ui 上传图片


在这里插入图片描述

  • 这玩意很简单,记录一下吧,给入门的小白用下

1.template 部分

<template>
  <div class="editPage__img">
    <div class="title">图片设置</div>
    <div class="img__con">
      <el-upload
        class="avatar-uploader"
        :action="uploadImgUrl"
        :data="uploadImgData"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <p><span>(点击图片即可替换其它图片)</span><br>说明:图片宽度为750PX,格式为JPG或者PNG,每张图片大小不超过3M</p>
    </div>
  </div>
</template>

2. script 部分

data() {
    return {
      imageUrl: this.rightData.imageUrl,
      // 图片上传
      uploadImgUrl: `${process.env.VUE_APP_BASE_API}/common-server/aliFile/upLoadFileNoSecret`,
      uploadImgData: { busiName: 32 },
      // 应付多个组件的情况 记录当前组件的key值
      componentKey: null,
    };
  },
  methods: {
    uploadImg() {},
    handleAvatarSuccess(res, file) {
      // console.log(res)
      this.imageUrl = res.data.url;
       this.$emit("childRightFn", {
        ...this.rightData,
        ...{ imageUrl: this.imageUrl}, 
        ...{props: {src: this.imageUrl}} 
      });
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
        // 限制只能3M以内的图片
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isJPG) {
        this.$message.error("图片只能是 JPG 或者 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 3MB!");
      }
      return isJPG && isLt2M;
    },
  },

3. scss 部分

  • 请大家按需取用,不需要删掉就是,不要原封不动的搬
<style lang="scss" scoped>
.editPage__img {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 16px;
    color: #8c939d;
    width: 350px;
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
  .avatar {
    width: 350px;
    height: auto;
    display: block;
  }
  .title {
    font-size: 18px;
    margin-bottom: 20px;
  }
  .img__con {
    p {
      margin-top: 10px;
      text-align: center;
      span{
        color: #409eff;
      }
    }
    .el-button {
      width: 100%;
      margin: 10px 0 20px 0;
    }
  }
}
</style>
  • 加了很多注释,相信大家问题不大了,有问题可以加主页的群直接问我就成

1. 希望本文能对大家有所帮助,如有错误,敬请指出

2. 原创不易,还请各位客官动动发财的小手支持一波(关注、评论、点赞、收藏)
3. 拜谢各位!后续将继续奉献优质好文
4. 如果存在疑问,可以私信我(主页有Q)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_35942348/article/details/123805983