DEV Community

loading...

Vue Form Builder

buphmin
I do things, usually involving buttons. All the while listening to power metal. Oh, and I like cats.
・2 min read

So I have been looking around for a good vue form builder and I have never really found one that does what I want it to do. Ultimately as a primarily full stack dev I end up having to make both the server side validation and the client side validation. The majority of the time I use client side validation for simple html5 validity checks. Anything more complex then HTML5 checks belong exclusively on the server side, especially since you will need that logic again anyways. What I want in a vue form builder is essentially is to have vue call a formatted API which then vue uses to create the form.

With that being said this is what I am thinking of creating: a set of vue components that each handle rendering a piece of the form, vuex to store the form state in the form of a module, and some helpers to make it easier to work with.

Here is a stubbed outline, excuse the naming and such as this is in pre-prototype phase.


import Vue from 'vue';
import Vuex from 'vuex';
import VueFormBuilderModule from 'vue-builder/Module'; //whatever this is named
import FormBuilder from 'vue-builder/FormBuilder';

Vue.use(vuex);

const store = new Vuex.Store({
  modules: {
    VueFormBuilderModule
  }
});

new Vue({
  store,
  el: "#app",
  async created() {
    try {
      let formData = await fetch("http://apiwebsite/form");
      this.$store.commit("addForm", {
        metadata: formData,
        formName: "myform"
      });
    } catch(e) {
      //catch errors, you know what to do ;)
    }
  }
});

Then in our template:

  <div id="app">
    <form-builder form-name="myform"></form-builder>
  </div>

Form builder then takes the the following example API response:

{
  "first_name": {
    "field_type": "input",
    "data": "John"
    "attributes": {
      "type": "text",
      "maxlength": 50
    }
  }
}

And turns into rendered HTML:

  <form name="myform">
   <input name="first_name" type="text" maxlength="50" value="John" />
  </form>

Of course the input being bound 2 ways with the vuex data. You need more fields then the api would just contain more. If you need to customize rendering then you would use the provided slots.

This way you can keep all the logic of building and validating your forms in one spot.

Let me know what you all think of this idea! Would it be something you would use presuming it was flexible enough? Of course this is intended to be a public repo and FOSS.

Discussion (0)