Skip to content

Instantly share code, notes, and snippets.

@lubien
Created March 27, 2020 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lubien/697eafdc57ba87079d1e1d2b12ba9bee to your computer and use it in GitHub Desktop.
Save lubien/697eafdc57ba87079d1e1d2b12ba9bee to your computer and use it in GitHub Desktop.
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