my-form elements as array

This commit is contained in:
Sebastian Frank 2017-11-07 12:58:17 +01:00
parent d65faa41b3
commit f49153603a
4 changed files with 50 additions and 24 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,16 +1,16 @@
<template>
<form @submit.prevent="submit()">
<div v-for="(item, key) in elements" :key="key">
<div v-for="(el, idx) in elements" :key="idx">
<component
:is="item.element"
:name="key"
:label="item.label"
:description="item.description"
:props="item.props"
v-model="formData[key]"
@validate="validateData(key)"
:invalid="formErrors[key]"
:validatorMessage="formErrors[key] ? formErrors[key].message : ''"
:is="el.element"
:name="el.key"
:label="el.label"
:description="el.description"
:props="el.props"
v-model="formData[el.key]"
@validate="validateData(el.key)"
:invalid="formErrors[el.key]"
:validatorMessage="formErrors[el.key] ? formErrors[el.key].message : ''"
>
</component>
</div>
@ -24,8 +24,14 @@
export default {
name: "MyForm",
props: {
elements: {
initData: {
type: Object,
default: () => {
return {};
}
},
elements: {
type: Array,
default: () => {
return [];
}
@ -45,16 +51,34 @@ export default {
},
data() {
return {
formData: {},
formErrors: {}
formData: this.initData,
formErrors: {},
elementsMap: {}
}
},
created() {
this.setOrder();
},
watch: {
elements() {
this.setOrder();
},
initData() {
this.formData = this.initData;
}
},
methods: {
setOrder() {
this.elementsMap = {};
for (let a in this.elements) {
this.elementsMap[this.elements[a].key] = this.elements[a];
}
},
validateData(name) {
if (this.elements[name].required) {
if (this.elementsMap[name].required) {
if (!this.formData[name]) {
this.$set(this.formErrors, name, {
message: this.elements[name].requiredMessage
message: this.elementsMap[name].requiredMessage
});
return false;
@ -73,7 +97,7 @@ export default {
},
submit() {
let valid = true;
Object.keys(this.elements).forEach(key => {
Object.keys(this.elementsMap).forEach(key => {
valid = (this.validateData(key) && valid);
});
if (valid) {

View File

@ -23,8 +23,9 @@ export default {
return {
username: "",
password: "",
elements: {
username: {
elements: [
{
key: "username",
element: "my-input",
icon: "icon-user",
required: true,
@ -34,7 +35,8 @@ export default {
placeholder: "Benutzername"
}
},
password: {
{
key: "password",
element: "my-input",
icon: "icon-key",
required: true,
@ -44,7 +46,7 @@ export default {
placeholder: "Passwort"
}
}
},
],
buttons: [{
label: "login",
type: "submit"