Created
March 27, 2020 23:30
-
-
Save lubien/697eafdc57ba87079d1e1d2b12ba9bee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function defaultDirtyForForm(form) { | |
return Object.keys(form).reduce((acc, key) => { | |
acc[key] = false; | |
return acc; | |
}, {}); | |
} | |
const WithForm = defaultForm => { | |
const fields = Object.keys(defaultForm()); | |
return { | |
defaultForm, | |
props: { | |
entity: { | |
type: [Boolean, Object] | |
} | |
}, | |
data() { | |
const form = this.$options.defaultForm(); | |
return { | |
form, | |
isDirty: defaultDirtyForForm(form) | |
}; | |
}, | |
computed: { | |
isEditing() { | |
return !!this.entity; | |
}, | |
isNew() { | |
return !this.isEditing; | |
}, | |
formDirty() { | |
return Object.values(this.isDirty).some(value => value); | |
}, | |
formValid() { | |
return Object.keys(this.form).every( | |
field => this[`${field}Validation`].state !== false | |
); | |
}, | |
...fields.reduce((acc, field) => { | |
acc[`${field}Validation`] = function validation() { | |
if (!this.isDirty[field]) { | |
return { state: null, messages: [] }; | |
} | |
let state = true; | |
const messages = []; | |
const validator = | |
this.$options.validateForm && this.$options.validateForm[field]; | |
if (validator && !validator(this.form.slug)) { | |
state = false; | |
messages.push("Inválido"); | |
} | |
return { state, messages }; | |
}; | |
return acc; | |
}, {}) | |
}, | |
methods: { | |
resetForm() { | |
const form = this.$options.defaultForm(); | |
const isDirty = defaultDirtyForForm(this.form); | |
if (this.entity) { | |
const cloned = JSON.parse(JSON.stringify(this.entity)); | |
for (let key of Object.keys(this.form)) { | |
form[key] = cloned[key]; | |
} | |
} | |
this.$set(this, "form", form); | |
this.$set(this, "isDirty", isDirty); | |
}, | |
dirty(key) { | |
this.isDirty[key] = true; | |
}, | |
stopEditing() { | |
this.$emit("stopEditing"); | |
} | |
}, | |
watch: { | |
entity() { | |
this.resetForm(); | |
} | |
} | |
}; | |
}; | |
export default WithForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment