el-upload上传文件+超过一张图隐藏上传按钮+必填校验

实现效果:
表单实现上传banner、logo及企业信息图功能,要求banner、logo为必填项,只允许上传一张图,超过一张隐藏上传按钮
el-upload上传文件+超过一张图隐藏上传按钮+必填校验_第1张图片 1. 页面区

<el-form class="g-form" ref="lstInfoForm" :rules="rules" :model="lstInfoForm" label-width="110px" v-loading="loading">
  <el-row :gutter="20">
    <el-col :span="6">
      <el-form-item label="上传LOGO:" class="pic-upload" prop="logoImg">
        <el-upload class="g-upload" ref="img2" :action="actionUrl" :headers="headers"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG" :on-success="onsuccess2" :on-remove="handleRemove2"
          :on-error="errorFunImage" :on-preview="handlePreview" :on-exceed="handleExceed" :limit="limit"
          :file-list="fileList2" list-type="picture-card" :multiple="false"
          :class="lstInfoForm.logo ? 'imgHide' : ''">
          <i class="el-icon-plus"></i>
        </el-upload>
        <div class="uploadTis">
          只能上传jpg/png文件,且不超过2M<br />
          建议尺寸:150px * 50 px</div>
      </el-form-item>
    </el-col>
  </el-row>
</el-form>
 <el-dialog :visible.sync="dialogVisible">
  	<img width="100%" :src="dialogImageUrl" alt="" />
 </el-dialog>

2. 表单验证

//这里采用的是自定义验证方法:validateFile2
rules: {
  logoImg: [
    { required: true, validator: validateFile2, trigger: "change" }
  ],
},

3. 自定义验证规则:validateFile2

data () {
    const validateFile2 = (rule, value, callback) => {
      if (!this.lstInfoForm.logo) {  //当'this.resourceForm.imageUrl'不等于‘true’
        callback(new Error("请上传图片"))
      } else {
        callback()
      }
    };
}

4. 方法

methods: {
    // 上传成功回调---lOGO
    onsuccess2 (res) {
      this.lstInfoForm.logo = res.data.url
      this.$message.success("上传成功");
    },
    // 删除---lOGO
    handleRemove2 (file, fileList) {
      this.lstInfoForm.logo = "";
      this.fileList2 = [];
      this.$refs.img2.clearFiles();
      this.$message.success("删除成功");
    },
    // 上传失败回调---封面图/lOGO/banner
    errorFunImage () {
      this.$message.error("上传失败");
      return false;
    },
    // 预览---封面图/lOGO/banner
    handlePreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件个数超出---封面图/lOGO/banner
    handleExceed () {
      this.$message.error(`上传文件数量不能超过 ${this.limit}!`);
    },
}

全部代码

<template>
  <!-- 企业专版编辑 -->
  <div class="consultingEdit manage-wrap">
    <ManageHeader :url-list="[{ name: 'title', url: $route.fullPath, label: '企业专版编辑' }]" />
    <!-- 列表信息 -->
    <div class="manageCon manageCon2">
      <div class="titArea mb30">
        <h2><cite class="mr10"></cite>列表信息</h2>
      </div>
      <el-form class="g-form" ref="lstInfoForm" :rules="rules" :model="lstInfoForm" label-width="110px"
        v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="企业简称:" prop="abbreviation">
              <el-input type="textarea" v-model="lstInfoForm.abbreviation" maxlength="12" autosize placeholder="请输入企业名称"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="企业简述:" prop="sketch">
              <el-input type="textarea" v-model="lstInfoForm.sketch" maxlength="20" autosize placeholder="请输入企业名称"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item prop="isConglomerate" label="集团企业">
              <el-radio-group v-model="lstInfoForm.isConglomerate">
                <el-radio label="1"></el-radio>
                <el-radio label="2"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span=" 18">
            <el-form-item label="企业类型" prop="enterpriseType">
              <el-select v-model="lstInfoForm.enterpriseType" placeholder="请选择企业类型">
                <el-option v-for="item in enterpriseLst" :key="item.code" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="上传banner:" class="pic-upload" prop="bannerImg">
              <el-upload class="g-upload" ref="img3" :action="actionUrl" :headers="headers"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG" :on-success="onsuccess3" :on-remove="handleRemove3"
                :on-error="errorFunImage" :on-preview="handlePreview" :on-exceed="handleExceed" :limit="limit"
                :file-list="fileList3" list-type="picture-card" :multiple="false"
                :class="lstInfoForm.imageUrl ? 'imgHide' : ''">
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 弹出框 -->
              <el-popover placement="right" trigger="click" popper-class="g-popover" v-model="popoverBanner">
                <div class="defaultBanner" id='g-scrollBar'>
                  <div class="default_box" v-for="(item, index) in bannerLst" :key="index">
                    <!-- <div class="default_box" v-for="(item, index) in bannerLst" :key="index"
                    :class="index >= 8 ? 'hidden' : ''"> -->
                    <el-image class="defaultImg" :src="item.imgUrl" fit="contain"
                      @click="chooseDefault(item, '1'), (popoverBanner = false)"></el-image>
                  </div>
                </div>
                <el-button type="primary" style="margin-top:8px;margin-left:7px;" slot="reference">选择默认图</el-button>
              </el-popover>
              <!-- 弹出框 -end--->
              <div class="uploadTis">
                只能上传jpg/png文件,且不超过2M<br />
                建议尺寸:1920px * 420 px</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上传LOGO:" class="pic-upload" prop="logoImg">
              <el-upload class="g-upload" ref="img2" :action="actionUrl" :headers="headers"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG" :on-success="onsuccess2" :on-remove="handleRemove2"
                :on-error="errorFunImage" :on-preview="handlePreview" :on-exceed="handleExceed" :limit="limit"
                :file-list="fileList2" list-type="picture-card" :multiple="false"
                :class="lstInfoForm.logo ? 'imgHide' : ''">
                <i class="el-icon-plus"></i>
              </el-upload>
              <div class="uploadTis">
                只能上传jpg/png文件,且不超过2M<br />
                建议尺寸:150px * 50 px</div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业信息图:" class="pic-upload">
              <el-upload class="g-upload" ref="img1" :action="actionUrl" :headers="headers"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG" :on-success="onsuccess1" :on-remove="handleRemove1"
                :on-error="errorFunImage" :on-preview="handlePreview" :on-exceed="handleExceed" :limit="limit"
                :file-list="fileList1" list-type="picture-card" :multiple="false"
                :class="lstInfoForm.coverPhoto ? 'imgHide' : ''">
                <i class="el-icon-plus"></i>
              </el-upload>
              <div class="uploadTis">
                只能上传jpg/png文件,且不超过2M<br />
                建议尺寸:480px * 300 px</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="企业全称:" prop="fullName">
              <el-input type="textarea" v-model="lstInfoForm.fullName" maxlength="40" autosize placeholder="请输入企业全称"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="企业愿景:">
              <el-input type="textarea" v-model="lstInfoForm.ourVision" maxlength="40" autosize placeholder="请输入企业愿景"
                show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="企业描述:" prop="describe">
              <el-input type="textarea" v-model="lstInfoForm.describe" maxlength="300" autosize placeholder="请输入企业描述"
                :autosize="{ minRows: 3, maxRows: 5}" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item>
              <el-button class="btn-save" type="primary" @click="submitFormInfo()">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <!-- 我们的优势 -->
    <div class="manageCon manageCon2">
      <advantage ref="advantage" />
    </div>
    <!-- 合作伙伴 -->
    <div class="manageCon manageCon2">
      <partner ref="partner" />
    </div>
  </div>
</template>
<script>
import { defaultImg } from "@/api/common";                         //默认图
import { addLstYG, modifyLstYG, queryInfoByCreateBy, listByTypeCode } from "@/api/enterprise";
import ManageHeader from "../components/plans/ManageHeader.vue";
import Advantage from './components/advantage.vue';
import Partner from './components/partner.vue';
import config from "@/config.vue";
export default {
  name: 'enterpriseAdd',
  components: {
    ManageHeader,
    Advantage,
    Partner,
  },
  data () {
    const validateFile1 = (rule, value, callback) => {
      if (!this.lstInfoForm.coverPhoto) {  //当'this.resourceForm.imageUrl'不等于‘true’
        callback(new Error("请上传图片"))
      } else {
        callback()
      }
    };
    const validateFile2 = (rule, value, callback) => {
      if (!this.lstInfoForm.logo) {  //当'this.resourceForm.imageUrl'不等于‘true’
        callback(new Error("请上传图片"))
      } else {
        callback()
      }
    };
    const validateFile3 = (rule, value, callback) => {
      if (!this.lstInfoForm.imageUrl) {  //当'this.resourceForm.imageUrl'不等于‘true’
        callback(new Error("请上传图片"))
      } else {
        callback()
      }
    };
    return {
      //默认banner图
      bannerLst: [],
      popoverBanner: false,
      //列表信息---
      lstInfoForm: {
        abbreviation: '',    //企业简称
        sketch: '',          //企业简述
        coverPhoto: '',      //封面图
        logo: '',            //LOGO
        imageUrl: '',        //banner
        fullName: '',        //企业全称
        ourVision: '',       //企业愿景
        describe: '',        //企业描述
        isConglomerate: '1', //是否为集团企业
        enterpriseType: '',  //企业类型
        add: 1,
      },
      //列表信息-rules
      rules: {
        abbreviation: [
          { required: true, message: '请输入企业简称', trigger: 'blur' },
          { min: 1, max: 12, message: '长度在 112 个字符', trigger: 'blur' }
        ],
        sketch: [
          { required: true, message: '请输入企业简述', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 120 个字符', trigger: 'blur' }
        ],
        isConglomerate: [
          { required: true, message: '请选择是否为集团企业', trigger: 'change' }
        ],
        enterpriseType: [
          { required: true, message: '请选择企业类型', trigger: 'change' }
        ],
        picImg: [
          { required: true, validator: validateFile1, trigger: "change" }
        ],
        logoImg: [
          { required: true, validator: validateFile2, trigger: "change" }
        ],
        bannerImg: [
          { required: true, validator: validateFile3, trigger: "change" }
        ],
        fullName: [
          { required: true, message: '请输入企业全称', trigger: 'blur' },
          { min: 1, max: 40, message: '长度在 140 个字符', trigger: 'blur' }
        ],
        // ourVision: [
        //   { required: true, message: '请输入企业愿景', trigger: 'blur' },
        //   { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' }
        // ],
        describe: [
          { required: true, message: '请输入企业描述', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1300 个字符', trigger: 'blur' }
        ],
      },
      // 上传图片--列表信息
      actionUrl: config.FILE + '/upload', // 上传的图片服务器地址
      headers: { Authorization: "Bearer" + localStorage.getItem("Authorization"), },
      dialogVisible: false,   //预览图片--遮罩
      dialogImageUrl: '',     //预览图片
      limit: 1,               //上传个数
      fileList1: [],          // 封面图列表
      fileList2: [],          // 上传lOGO列表
      fileList3: [],          // 上传banner
      enterpriseLst: [],      //企业类型
      //loading
      loading: false,
    }
  },
  computed: {},
  created () {
  },
  mounted () {
    this.getQueryInfoByCreateBy(); //获取列表信息
    this.getDefaultImg();          //获取默认头像
    this.getListByTypeCode();      //获取企业类型列表
  },
  methods: {
    // 换默认图方法
    chooseDefault (item, type) {
      let url = item.imgUrl;
      //console.log(6666, url);
      if (type == '1') {
        this.fileList3 = [{ url: url }]
        this.lstInfoForm.imageUrl = url
      }
    },
    //获取默认头像
    getDefaultImg () {
      let that = this
      this.loading = true;
      defaultImg({ moduleType: '1' }).then(res => {
        if (res.code === 200) {
          this.loading = false;
          //console.log(6666, res);
          this.bannerLst = res.data
        } else {
          this.loading = false;
          this.$message.error(res.mgs)
        }
      }).catch((e) => {
        that.loading = false;
        console.log(e)
      });
    },
    //获取企业类型列表
    getListByTypeCode () {
      let that = this
      listByTypeCode({ typeCode: "enterpriseType" }).then(res => {
        if (res.code === 200) {
          this.loading = false;
          const result = res.data
          //console.log(6666, res);
          this.enterpriseLst = result

        } else {
          this.loading = false;
          this.$message.error(res.mgs)
        }
      }).catch((e) => {
        that.loading = false;
        console.log(e)
      });
    },
    //获取列表信息
    getQueryInfoByCreateBy () {
      let that = this
      this.loading = true;
      queryInfoByCreateBy({}).then(res => {
        this.loading = false;
        if (res.code === 200) {
          if (res.data) {
            const result = res.data
            this.lstInfoForm = result
            console.log('555', this.lstInfoForm)
            if (result.coverPhoto) {
              this.fileList1 = [{
                url: result.coverPhoto
              }]
            }
            if (result.logo) {
              this.fileList2 = [{
                url: result.logo
              }]
            }
            if (result.imageUrl) {
              this.fileList3 = [{
                url: result.imageUrl
              }]
            }
          } else {
            this.lstInfoForm = {
              abbreviation: '',  //企业简称
              sketch: '',        //企业简述
              coverPhoto: '',    //封面图
              logo: '',          //LOGO
              imageUrl: '',      //banner
              fullName: '',      //企业全称
              ourVision: '',     //企业愿景
              describe: '',      //企业描述
              isConglomerate: '1', //是否为集团企业
              enterpriseType: '',//企业类型
              add: 1,
            }
          }
        }
      }).catch((e) => {
        that.loading = false;
        console.log(e)
      });
    },
    //列表信息--表单提交
    submitFormInfo () {
      const that = this
      this.$refs.lstInfoForm.validate((valid) => {
        if (valid) {
          const data = {
            ...this.lstInfoForm
          }
          this.loading = true;
          this.$confirm('确认将列表信息保存并提交审核?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.lstInfoForm.add === 1) {
              addLstYG(data).then(res => {
                this.loading = false;
                if (res.code === 200) {
                  this.$message.success('新增成功,请等待审核通过!')
                  this.getQueryInfoByCreateBy()
                } else {
                  this.$message.error(res.mgs)
                }
              })
            } else {
              modifyLstYG(data).then(res => {
                this.loading = false;
                if (res.code === 200) {
                  this.$message.success('修改成功,请等待审核通过!')
                  this.getQueryInfoByCreateBy()
                } else {
                  this.$message.error(res.mgs)
                }
              })
            }
          }).catch((e) => {
            that.loading = false
            console.log(e)
          });
        }
      });
    },
    // 上传成功回调---封面图
    onsuccess1 (res) {
      this.lstInfoForm.coverPhoto = res.data.url;
      this.fileList1.push({ name: res.data.name, url: res.data.url });
      this.$message.success("上传成功");
    },
    // 删除---封面图
    handleRemove1 (file, fileList) {
      this.lstInfoForm.coverPhoto = "";
      this.fileList1 = [];
      this.$refs.img1.clearFiles();
      this.$message.success("删除成功");
    },
    // 上传成功回调---lOGO
    onsuccess2 (res) {
      this.lstInfoForm.logo = res.data.url
      this.$message.success("上传成功");
    },
    // 删除---lOGO
    handleRemove2 (file, fileList) {
      this.lstInfoForm.logo = "";
      this.fileList2 = [];
      this.$refs.img2.clearFiles();
      this.$message.success("删除成功");
    },
    // 上传成功回调---banner
    onsuccess3 (res) {
      //this.fileList3.push({ name: res.data.name, url: res.data.url });
      this.lstInfoForm.imageUrl = res.data.url
      this.$message.success("上传成功");
    },
    // 删除---banner
    handleRemove3 (file, fileList) {
      this.lstInfoForm.imageUrl = "";
      this.fileList3 = [];
      this.$refs.img3.clearFiles();
      this.$message.success("删除成功");
    },
    // 上传失败回调---封面图/lOGO/banner
    errorFunImage () {
      this.$message.error("上传失败");
      return false;
    },
    // 预览---封面图/lOGO/banner
    handlePreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件个数超出---封面图/lOGO/banner
    handleExceed () {
      this.$message.error(`上传文件数量不能超过 ${this.limit}!`);
    },
  }
}
</script>
<style  scoped>
@import "~assets/css/manage.css";
//超过一张图隐藏上传按钮
.pic-upload  .imgHide .el-upload--picture-card {
  display: none;
}
</style>

你可能感兴趣的:(前端,javascript,vue.js,elementui)