Table of Contents

Overview

We developers always find ways to get things done quickly and efficiently. Keeping the need for easy form generation in lesser time, here’s a tutorial for you! A few days back, there was a client requirement for integrating form and customizing it in the project using vuetify-jsonschema-form. Searching for a proper informative tutorial for the same was a real struggle. The task was done with efficiency within the deadline. But, the thought crossed my mind what if another fellow developer might face this same issue. So, to lessen their struggle and smoothen the process here’s a form generation using JSON schema in VueJS that will show a hustle-free technique of implementing vuetify-jsonschema-form to generate and customize the form.

Here are some benefits of implementing vuetify-jsonschema-form:

  • Supports all basic data types.
  • Allows the implementation of nested objects and nested arrays.
  • Supports different display options.
  • Supports validation against the provided schema.
  • Allows content injection using slots.
  • Provides consistency and reusability.

There are many packages that support jsonSchema. But, here in this tutorial, we will discuss @koumoul/vuetify-jsonschema-form and implement a few advanced features.

Initial Set-Up

For initial set-up, use the below-mentioned commands.

(If vue-cli is not already installed, npm install -g @vue/cli)

Copy Text
vue create schema-app
cd schema-app

Install Dependencies

Now it’s time to install vuetify and vuetify-jsonschema-form. For that, fire the below commands.

Copy Text
vue add vuetify

npm i --save @koumoul/vuetify-jsonschema-form

Since this is a small demo application, the folder structure will be quite simple. Here’s the basic structure.

Install Dependencies

And main.js will look like this:

Copy Text
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify'

Vue.config.productionTip = false

new Vue({
  vuetify,
  render: h => h(App)
}).$mount('#app')

Configure SchemaForm.vue

SchemaForm.vue will be our main component which would have logic and UI of the demo. Import the needed dependencies and CSS file in SchemaForm.vue component as shown below.

// SchemaForm.vue

Copy Text
 import Vue from 'vue'
  import Vuetify from 'vuetify'
  import 'vuetify/dist/vuetify.min.css'
  import Draggable from 'vuedraggable'
  import Swatches from 'vue-swatches'
  import 'vue-swatches/dist/vue-swatches.min.css'
  import VJsonschemaForm from '@koumoul/vuetify-jsonschema-form'
  import '@koumoul/vuetify-jsonschema-form/dist/main.css'
  import { Sketch } from 'vue-color'

  Vue.use(Vuetify)

  Vue.component('swatches', Swatches)
  Vue.component('draggable', Draggable)
  Vue.component('color-picker', Sketch)

  export default {
    name: 'SchemaForm',
    components: {
      VJsonschemaForm,
    },
}

Are you looking for skilled and dedicated VueJS developers?
Hire VueJS developer from us to smoothen your development process and to build feature-rich real-time applications

Passing Values to Props

After importing the package, it’s time to use it. The package provides the to which you can pass values to its props.

Copy Text
<template>
  <v-container>
    <h2>Create Form using json-schema</h2>
    <v-jsonschema-form
      v-if="
        schemaData &&
          Object.keys(schemaData).length > 0
      "
      :schema="schemaData"
      :model="modelData"
      :options="schemaOptions"
    />
    <v-btn color="light-blue" @click="saveJson">Save</v-btn
    >
  </v-container>
</template>

Explanation:

  • v-if will check whether there are properties in schemaData or not.
  • Schema prop the library understands this schema prop as the structure of your your form fields. Here, the schema prop takes schemaData object as the value and thus the UI displays the given fields.
  • Model prop stands for the values we fill in the form which we will be acquired in the modelData object. So whatever data entered by the user will be stored in the modelData and further send to model prop.
  • Options prop stands for the additional options that we want to give.

Example:

Copy Text
schemaOptions : {
        debug: false,
        disableAll: false,
        autoFoldObjects: true
}

Here, is the initial data and methods defined in the demo.

Copy Text
    data: () => ({
      schemaData: require("./schema"),
      modelData: {},
      schemaOptions: {
        "accordionMode": "normal"
      }
    }),

Here schemaData will fetch the form fields which we have defined in the schema.json. So, the structure of our form is decided from whatever fields and types we define in the JSON file.

Let’s have a look at our schema.json file.

// schema.json

Copy Text
{
  "type": "object",
  "title": "",
  "required": ["Name"],
  "properties": {
    "Name": {
      "type": "string",
      "title": "Name "
    },
     "Gender": {
      "type": "string",
      "title": "Gender ",
      "enum": ["Male", "Female", "Other"],
      "attrs": {
        "placeholder": "Select gender",
        "title": "Please select gender"
      }
    },
    "FavColor": {
      "title": "Select favourite color using color picker",
      "description": "In hex format",
      "type": "string",
      "format": "hexcolor",
      "x-display": "color-picker"
    },
    "Active": {
      "type": "boolean",
      "title": "Profile Active?",
      "description": "",
      "default": true,
      "attrs": {
        "type": "switch"
      }
    },
    "Hobby": {
      "type": "array",
      "title": "Hobbies",
      "items": {
        "$ref": "#/definitions/hobby"
      }
    },
    "PaymentInfo": {
      "type": "object",
      "title": "Payment Info",
      "oneOf": [
        {
          "$ref": "#/definitions/creditCard"
        },
        {
          "$ref": "#/definitions/upi"
        }
      ]
    }
  },
  "definitions": {
    "hobby": {
      "type": "object",
      "properties": {
        "Hobby": {
          "type": "string"
        },
        "isCertified": {
          "title": "Is certified?",
          "type": "boolean"
        }
      }
    },
    "creditCard": {
      "title": "Main infos",
      "properties": {
        "address": {
          "type": "string",
          "maxLength": 2000
        },
        "credit_card": {
          "type": "number"
        }
      },
      "dependencies": {
        "credit_card": {
          "properties": {
            "billing_address": {
              "type": "string"
            }
          },
          "required": ["billing_address"]
        }
      }
    },
    "upi": {
      "title": "UPI",
      "properties": {
        "upiId": {
          "type": "string"
        }
      }
    }
  }
}

For this form schema, we can directly define the type, if required without worrying about its HTML. Like, Date-time, Drop Down, Color picker, Range selector, Switch, etc.

Here, the field Hobby is an array of objects which is defined later in definitions.PaymentInfo field lets us select one of the references (CreditCard/UPI). It also supports dependent fields, if we want to display other fields on conditional basis, for example, billing-address will only be displayed if the credit-card number is entered. It also saves time for both Frontend and Backend developers for saving and pre-filling forms.

So, this was about form generation using JSON schema in VueJS. There’s still a lot more advanced features and properties offered by vuetify-jsonschema-form. This was just a basic implementation of it. Feel free to explore more and generated forms.

Github Repository: Form Generation using JSON Schema in VueJS

You can visit here – Github Repository and play around with code or follow the steps mentioned above for developing the application.

Conclusion

I hope this tutorial on form generation using JSON schema in VueJS has helped you get started with the package. Keep reading our tutorials to gain fundamental and advanced VueJS knowledge.  With every tutorial, we will provide you with a github repository so that you can clone and play around with the code. Bacancy is the best Vue.js development company offering dedicated and skilled VueJS developers to build high-performance applications. Get in touch with us if you are looking for proficient VueJs developers.

Vue JS Tutorials

View the VueJS framework with Optimized Perspectives

Explore Now

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?