element/packages/form/src/form.vue

103 lines
2.4 KiB
Vue
Raw Normal View History

2016-07-27 06:15:02 +00:00
<template>
2016-08-29 11:19:14 +00:00
<form class="el-form" :class="[
labelPosition ? 'el-form--label-' + labelPosition : '',
{ 'el-form--inline': inline }
2016-07-27 06:15:02 +00:00
]">
<slot></slot>
</form>
</template>
<script>
export default {
name: 'ElForm',
2016-11-26 07:18:38 +00:00
componentName: 'ElForm',
2016-07-27 06:15:02 +00:00
2017-09-17 16:47:37 +00:00
provide() {
return {
elForm: this
};
},
2016-07-27 06:15:02 +00:00
props: {
model: Object,
rules: Object,
2016-08-29 11:19:14 +00:00
labelPosition: String,
2016-07-27 06:15:02 +00:00
labelWidth: String,
labelSuffix: {
type: String,
default: ''
2016-08-29 11:19:14 +00:00
},
2017-01-11 18:34:15 +00:00
inline: Boolean,
inlineMessage: Boolean,
statusIcon: Boolean,
2017-01-11 18:34:15 +00:00
showMessage: {
type: Boolean,
default: true
}
2016-07-27 06:15:02 +00:00
},
watch: {
rules() {
this.validate();
}
},
2016-07-27 06:15:02 +00:00
data() {
return {
2016-11-26 02:48:06 +00:00
fields: []
2016-07-27 06:15:02 +00:00
};
},
2016-08-16 13:07:27 +00:00
created() {
this.$on('el.form.addField', (field) => {
2016-11-26 02:48:06 +00:00
if (field) {
this.fields.push(field);
}
2016-08-16 13:07:27 +00:00
});
/* istanbul ignore next */
2016-08-16 13:07:27 +00:00
this.$on('el.form.removeField', (field) => {
2016-11-26 02:48:06 +00:00
if (field.prop) {
this.fields.splice(this.fields.indexOf(field), 1);
}
2016-08-16 13:07:27 +00:00
});
2016-07-27 06:15:02 +00:00
},
methods: {
2016-08-16 13:07:27 +00:00
resetFields() {
2017-06-18 09:48:18 +00:00
if (!this.model) {
process.env.NODE_ENV !== 'production' &&
console.warn('[Element Warn][Form]model is required for resetFields to work.');
return;
}
2016-11-26 02:48:06 +00:00
this.fields.forEach(field => {
2016-07-27 06:15:02 +00:00
field.resetField();
2016-11-26 02:48:06 +00:00
});
2016-07-27 06:15:02 +00:00
},
validate(callback) {
if (!this.model) {
console.warn('[Element Warn][Form]model is required for validate to work!');
return;
};
2016-11-26 02:48:06 +00:00
let valid = true;
2016-12-22 16:49:45 +00:00
let count = 0;
// 如果需要验证的fields为空调用验证时立刻返回callback
if (this.fields.length === 0 && callback) {
callback(true);
}
2016-11-26 02:48:06 +00:00
this.fields.forEach((field, index) => {
2016-07-27 06:15:02 +00:00
field.validate('', errors => {
if (errors) {
valid = false;
}
2016-12-22 16:49:45 +00:00
if (typeof callback === 'function' && ++count === this.fields.length) {
2016-07-27 06:15:02 +00:00
callback(valid);
}
});
2016-11-26 02:48:06 +00:00
});
2016-07-27 06:15:02 +00:00
},
validateField(prop, cb) {
2016-11-26 02:48:06 +00:00
var field = this.fields.filter(field => field.prop === prop)[0];
2016-07-27 06:15:02 +00:00
if (!field) { throw new Error('must call validateField with valid prop string!'); }
field.validate('', cb);
}
}
};
</script>