<template>
<view class="u-form"><slot /></view>
</template>
<script>
export default {
name: 'u-form',
props: {
model: {
type: Object,
default() {
return {};
}
},
errorType: {
type: Array,
default() {
return ['message', 'toast']
}
},
borderBottom: {
type: Boolean,
default: false
},
labelPosition: {
type: String,
default: 'left'
},
labelWidth: {
type: [String, Number],
default: 25
},
labelAlign: {
type: String,
default: 'left'
},
labelStyle: {
type: Object,
default() {
return {}
}
},
},
provide() {
return {
uForm: this
};
},
data() {
return {
rules: {}
};
},
created() {
this.fields = [];
let that = this;
this.$on('on-form-item-add', item => {
if (item) {
that.fields.push(item);
}
});
this.$on('on-form-item-remove', item => {
if (item.prop) {
that.fields.splice(that.fields.indexOf(item), 1);
}
});
},
methods: {
setRules(rules) {
this.rules = rules;
},
resetFields() {
this.fields.map(field => {
field.resetField();
});
},
validate(callback) {
return new Promise(resolve => {
let valid = true;
let count = 0;
let errorArr = [];
this.fields.map(field => {
field.validation('', error => {
if (error) {
valid = false;
errorArr.push(error);
}
if (++count === this.fields.length) {
resolve(valid);
if(this.errorType.indexOf('none') === -1 && this.errorType.indexOf('toast') >= 0 && errorArr.length) {
this.$u.toast(errorArr[0]);
}
if (typeof callback == 'function') callback(valid);
}
});
});
});
}
}
};
</script>
<style scoped lang="scss">
@import "../../libs/css/style.components.scss";
</style>