validate 函数。继续看 FormItem.vue 这个文件:
<template>
<div>
<label v-if="label">{{ label }}</label>
<div>
<slot></slot>
<p v-if="validateState === 'error' " class="error">{{ validateMessage }}</p>
</div>
</div>
</template><script>
import AsyncValidator from "async-validator";
export default {
name: "EFormItem",
props: {
label: { type: String, default: '' },
prop: { type: String, default: '' }
},
inject: ["eForm"], // 解释一
created() {
this.$on("validate", this.validate);
},
mounted() { // 解释二
if (this.prop) { // 解释三
this.dispatch('EForm', 'addFiled', this);
}
},
data() {
return {
validateMessage: "",
validateState: ""
};
},
methods: {
validate() {
// 解释四
return new Promise(resolve => {
// 解释五
const descriptor = {
// name: this.form.rules.name =>
// name: [ { require: true }, { ... } ] };
descriptor[this.prop] = this.eForm.rules[this.prop];
// 校验器
const validator = new AsyncValidator(descriptor);
const model = {};
model[this.prop] = this.eForm.model[this.prop];
// 异步校验
validator.validate(model, errors => {
if (errors) {
this.validateState = "error";
this.validateMessage = errors[0].message;
resolve(false);
} else {
this.validateState = "";
this.validateMessage = "";
resolve(true);
}
});
});
},
// 查找上级指定名称的组件
dispatch(componentName, eventName, params) {
var parent = this.$parent || this.$root;
var name = parent.$options.name;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.name;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
}
}
};
</script>
<style scoped>
.error {
color: red;
}
</style>
我们对上面的代码做一个解释。
解释一:注入
Form 组件提供的数据 –
Form 组件的实例,下面就可以使用
this.eForm.xxx 来使用
Form 中的数据了。解释二:因为我们需要在
Form 组件中校验所有的
FormItem










