Skip to content

Instantly share code, notes, and snippets.

@jblyberg
Last active January 17, 2020 19:56
Show Gist options
  • Save jblyberg/a438948d04d334ace8f5b483e6d43794 to your computer and use it in GitHub Desktop.
Save jblyberg/a438948d04d334ace8f5b483e6d43794 to your computer and use it in GitHub Desktop.
Form state tracker for use with Vue components using Vue composition API (or Vue 3)

Tracks form state data using the vue composition api (vue 3)

Example usage:

export default {
  setup() {
    const formState = reactive(new FormState());

    onMounted(async () => {
      const initialData = await someApiCall();
      formState.init(initialData);
    });

    const onSubmit = async () => {
      formState.submit();
      // Do stuff
      formState.init(formState.formVals);
    };

    const onReset = () => {
      formState.reset();
    };

    return { formState, onSubmit, onReset };
  },
};

Use formState.formVals to access your data in the template. The following computed properties can be used the the template as well:

formState.disabled
formState.submitted
formState.submittable
import { computed } from '@vue/composition-api';
import { isEqual } from 'lodash';
export default class FormState {
constructor() {
this.initialFormVals = {};
this.formVals = {};
this.loading = true;
this.submitted = false;
this.changed = computed(() => {
return !isEqual(this.initialFormVals, this.formVals);
});
this.disabled = computed(() => {
return !this.changed;
});
this.submittable = computed(() => {
return this.changed && !this.submitted;
});
}
init(initialFormVals) {
this.initialFormVals = this.clone(initialFormVals);
this.formVals = this.clone(initialFormVals);
this.loading = false;
this.submitted = false;
}
reset() {
this.formVals = this.clone(this.initialFormVals);
}
submit() {
this.submitted = true;
}
clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment