form.vue
2.85 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<template>
<form :class="classes" @submit="formSubmit"><slot></slot></form>
</template>
<script>
// https://github.com/ElemeFE/element/blob/dev/packages/form/src/form.vue
import { oneOf } from '../../utils/assist';
const prefixCls = 'ivu-form';
export default {
name: 'iForm',
props: {
model: {
type: Object
},
rules: {
type: Object
},
labelWidth: {
type: Number
},
labelPosition: {
validator (value) {
return oneOf(value, ['left', 'right', 'top']);
},
default: 'right'
},
inline: {
type: Boolean,
default: false
},
showMessage: {
type: Boolean,
default: true
}
},
data () {
return {
fields: []
};
},
computed: {
classes () {
return [
`${prefixCls}`,
`${prefixCls}-label-${this.labelPosition}`,
{
[`${prefixCls}-inline`]: this.inline
}
];
}
},
methods: {
resetFields() {
this.fields.forEach(field => {
field.resetField();
});
},
validate(callback) {
let valid = true;
let count = 0;
this.fields.forEach(field => {
field.validate('', errors => {
if (errors) {
valid = false;
}
if (typeof callback === 'function' && ++count === this.fields.length) {
callback(valid);
}
});
});
},
validateField(prop, cb) {
const field = this.fields.filter(field => field.prop === prop)[0];
if (!field) { throw new Error('[iView warn]: must call validateField with valid prop string!'); }
field.validate('', cb);
},
formSubmit (event) {
event.preventDefault();
}
},
watch: {
rules() {
this.validate();
}
},
created () {
this.$on('on-form-item-add', (field) => {
if (field) this.fields.push(field);
return false;
});
this.$on('on-form-item-remove', (field) => {
if (field.prop) this.fields.splice(this.fields.indexOf(field), 1);
return false;
});
}
};
</script>