場景:elementui表單元素change時調用接口獲取接口數據之后,表單規則驗證接口數據
change函數在調用接口獲取數據之后,利用validateField,單個元素進行驗證接口數據
1.頁面元素
<el-form-item label="xxxx" prop="projectId"> <el-select :disabled="actionType==='update'?true:false" v-model="planFormData.projectId" @change="getProjectDetail(planFormData.projectId)" placeholder="請選擇" > <el-option v-for="item in projectList" :label="item.name" :value="item.code" :key="item.code" ></el-option> </el-select> </el-form-item>
2.驗證字段
rules: { projectId: [ { required: true, message: "請選擇xxxx", trigger: "change" }, { required: true, validator: checkHasSeted, trigger: "change", }, ], }
3.驗證規則
var checkHasSeted = async (rule, value, callback) => { // var that = this; // await this.getHasSeted(this.planFormData.projectId); if (this.hasSeted) { if (this.isClick) { this.$message({ message: "xxxxxxxx", type: "error", }); } return callback(new Error("xxxxxxxx")); } else if (!this.hasAccount) { return callback(new Error("xxxxxxxx")); } else { callback(); } };
4.change函數,獲取接口數據之后利用validateField,驗證單個元素
// 獲取xxxx詳情 async getProjectDetail(id) { this.hasSeted = false; await this.getProjectInfo(id);//獲取數據 this.getAllocationCircle("first"); this.$refs.planForm.validateField("projectId", (valid) => {//表單驗證 // console.log(111,valid); }); },