1. 程式人生 > 其它 >elementUI自定義表單驗證,父元件控制多個子元件表單驗證

elementUI自定義表單驗證,父元件控制多個子元件表單驗證

//基礎資訊子元件
<template>
  <div class='BasisInfo'>
    <div class="basis-info-wrap">
      <div class="basis-info-title">基礎資訊</div>
      <el-form ref="ruleForm"
               size="mini"
               :model="ruleForm"
               :rules="rules"
               label-width="250px">
        <el-form-item label="店鋪logo"
                      prop='shopLogo'>
          <div class="upload-wrap content">
            <upload-file @upload-ok="uploadOk"
                         :class="{'el-input__inner':!logo}"
                         v-if="!ruleForm.shopLogo"></upload-file>
            <ul class="upload-img-list"
                v-else>
              <li class="item">
                <sup class="del"
                     @click="delLicenseImage"></sup>
                <img :src="ruleForm.shopLogo"
                     alt="">
              </li>
            </ul>
            <span class="upload-rule"><span @click="$emit('showLogoRule','logo')">店鋪logo上傳規則</span></span>
          </div>
          <div class="remind">
            請上傳格式為(.gif,.png,.jpg,.jpeg)、大小在1M以下、規格為<span class='logo-size-remind'>寬高為144x144畫素</span>的圖片
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import uploadFile from 'vues/components/uploadFile.vue';
const logoValid = (rule, value, back) => {
  if (!value) {
    back(new Error('店鋪logo不能為空,請重新確認'));
  } else {
    back();   //這裡記得呼叫back函式,否則父元件的getFormPromise無法正常呼叫validate裡面函式
  }
};

const _data = {
  logo: false,
  rules: {
    shopLogo: [
      {
        required: true,
        validator: logoValid,
        trigger: 'change'
      }
    ],
  }
};

export default {
  name: 'BasisInfo',
  components: { uploadFile },
  filters: {},
  props: {
    ruleForm: {
      type: Object,
      default() {
        return {
          shopName: '', // 店鋪名稱
          shopLogo: '', // 店鋪Logo
          shopMainCategory: '', // 店鋪主營分類
          shopMainBrand: '', // 店鋪主品牌
          shopDesc: '' // 店鋪簡介
        };
      }
    }
  },
  data() {
    return _data;
  },
  computed: {
    uploadUrl() {
      return window.UPLOADSERVER;
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    uploadOk(data) {
      console.log(data);
      this.ruleForm.shopLogo = data.Data;
    },
    delLicenseImage() {
      this.ruleForm.shopLogo = '';
    },
    beforeAvatarUpload(file) {
    }
  }
};
//聯絡方式子元件
<template>
  <!-- 聯絡方式 -->
  <div class='ContactWay'>
    <div class="contact-way-wrap">
      <div class="basis-info-title">聯絡方式</div>
      <el-form ref="ruleForm"
               size="mini"
               :model="ruleForm"
               :rules="rules"
               label-width="250px">
        <el-form-item label="緊急聯絡人"
                      prop="emergencyContact">
          <el-input v-model="ruleForm.emergencyContact"></el-input>
        </el-form-item>
        <el-form-item label="緊急聯絡人手機"
                      prop="emergencyContactPhone">
          <el-input v-model="ruleForm.emergencyContactPhone"></el-input>
        </el-form-item>
        <!-- /bc/baseConfig/shopInfo 這裡有地址介面 -->
        <el-form-item label="聯絡人地址">
          <div class="address-wrap">
            <el-cascader v-model="value"
                         :options="options"
                         @change="handleChange"></el-cascader>
          </div>
          <el-input type="textarea"
                    class="textarea"
                    placeholder="請輸入詳細地址"
                    v-model="ruleForm.emergencyAddress"></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
const _data = {
  rules: {
    emergencyContact: [
      {
        required: true,
        message: '店鋪簡介不能為空,請重新確認',
        trigger: 'blur'
      }
    ],
    emergencyContactPhone: [
      {
        required: true,
        message: '緊急聯絡人不能為空,請重新確認',
        trigger: 'blur'
      }
    ]
  }
};
export default {
  name: 'ContactWay',
  components: {},
  filters: {},
  props: {
    ruleForm: {
      type: Object,
      default() {
        return {
          emergencyContact: '', // 緊急聯絡人
          emergencyContactPhone: '', // 緊急聯絡電話
          emergencyAddress: '' // 詳細地址
        };
      }
    }
  },
  data() {
    return _data;
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {}
};
</script>
//父元件
<template>
      <!-- 基礎資訊 開始 -->
      <basis-info @showNameRule="showRule"
                  @showIntroduceRule="showRule"
                  @showLogoRule="showRule"
                  :ruleForm="submitParams"
                  ref="basisInfo" />
      <!-- 基礎資訊 結束 -->
      <!-- 聯絡方式 開始 -->
      <contact-way :ruleForm="submitParams"
                   ref="ContactWay" />
      <!-- 聯絡方式 結束 -->
</template>

<script>
...
methods:{
   // 提交店鋪資訊
    async submitStoreInfo() {
      const basisInfoForm = this.$refs.basisInfo.$refs.ruleForm;
      const contactWayForm = this.$refs.ContactWay.$refs.ruleForm;
      Promise.all(
        [basisInfoForm, contactWayForm].map(this.getFormPromise)
      ).then(async res => {
        const result = res.every(n => n);
        if (result) {
          console.log('表單驗證通過');
        } else {
          console.log('表單驗證不通過');
        }
      });
    },
    //驗證不同元件的表單
    getFormPromise(form) {
      return new Promise(resolve => {
      //傳入callback函式
        form.validate(res => {
          resolve(res); 
        });
      });
    }
}
...
</script>
注:以上內容僅用於日常學習