el-form設置規則校驗,在父子組件中多個表單需同時校驗


 

如上:

數據源和格式化分別在不同的兩個子組件中,同時引用在了父組件中,需要在父組件中點擊確定按鈕時,校驗父組件及兩個子組件中的表單是否均滿足校驗。

使用el-form的:rules="rules"結合this.$refs[formName].validate((valid) => {}來做。

 

實現代碼:

1.父組件設置rules規則,然后傳入每個子組件:

引用子組件

<!-- 數據源 -->
<div class="data_source">
  <Com-template-data-source
    ref="ComTemplateDataSourceRef"
    :rules="rules"
    :component-type="componentType"
    :sourceType="sourceType"
  />
</div>
<!-- 格式化 -->
<div class="formatting">
  <div class="top_title">格式化</div>
  <Com-template-format
    ref="ComTemplateFormatRef"
    :rules="rules"
    :component-type="componentType"
  />
</div>

 父組件中設置rules規則

rules: {
  componentName: [
    // 組件名稱
    { required: true, message: "請輸入組件名稱", trigger: "blur" },
  ],
  reportId: [
    // 報表id
    { required: true, message: "請選擇報表id", trigger: "blur" },
  ],
  groupOne: [
    // 一級分組
    { required: true, message: "請選擇一級分組", trigger: "blur" },
  ],
  valueData: [
    // 統計值
    { required: true, message: "請選擇統計值", trigger: "blur" },
  ],
  unit: [
    // 顯示單位
    { required: true, message: "請選擇顯示單位", trigger: "blur" },
  ],
  sortingCondition: [
    // 排序條件
    { required: true, message: "請選擇排序條件", trigger: "blur" },
  ],
},

2.在父組件中點擊確定時判斷是否均滿足校驗:

// 當前彈框form校驗
const p1 = new Promise((resolve, reject) => {
  this.$refs["form"].validate((valid) => {
    if (valid) resolve();
  });
});
// 數據源組件form校驗
const p2 = new Promise((resolve, reject) => {
  this.$refs["ComTemplateDataSourceRef"].$refs["form"].validate(
    (valid) => {
      if (valid) resolve();
    }
  );
});
// 格式化組件form校驗
const p3 = new Promise((resolve, reject) => {
  this.$refs["ComTemplateFormatRef"].$refs["form"].validate((valid) => {
    if (valid) resolve();
  });
});

Promise.all([p1, p2, p3]).then(async () => {
  // 做處理
});

 

注意:

1.在elementui中只有對一個表單的校驗,當對多個表單校驗且屬於不同的組件中時,可以采用上述辦法,通過refs獲取到對應的子組件,然后在el-form中設置ref="form",在獲取到子組件時再通過refs獲取到組件中的form表單,即可判斷是否滿足校驗規則了。

2.其實不分為多個子組件來寫也是可以的,這樣可以直接在一個form中做校驗,但是由於考慮到數據操作方法過多,會比較不好維護辨認,所以分離出多個子組件來做。

2.設置校驗需要幾部分::rules="rules"、ref="form"、prop="name"、this.$refs[formName].validate((valid)。

3.參考博客:https://www.cnblogs.com/junechen/p/11005324.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM