-
Notifications
You must be signed in to change notification settings - Fork 322
/
Copy pathKFormItem.vue
59 lines (55 loc) · 1.05 KB
/
KFormItem.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<template>
<div>
<!-- label -->
<label v-if="label">{{label}}</label>
<slot></slot>
<!-- 错误信息 -->
<p class="error" v-if="error">{{error}}</p>
</div>
</template>
<script>
import Validator from "async-validator";
export default {
inject: ["form"],
data() {
return {
error: ""
};
},
props: {
label: {
type: String,
default: ""
},
prop: String
},
mounted() {
this.$on("validate", () => {
this.validate();
});
},
methods: {
validate() {
// 校验规则
const rules = this.form.rules[this.prop];
// 当前值
const value = this.form.model[this.prop];
// 创建一个校验器实例
const validator = new Validator({ [this.prop]: rules });
// 校验, 返回Promise
return validator.validate({ [this.prop]: value}, errors => {
if (errors) {
this.error = errors[0].message
} else {
this.error = ''
}
})
}
}
};
</script>
<style scoped>
.error {
color: red;
}
</style>