How to create "Dynamic Forms" using Vue js
Before creating dynamic forms:
To create dynamic-forms first you need all the components available with you like text input, number input, radio buttons etc.. or choose a library that works for you like Element UI, vuetifyjs.com which does the job.
Steps to create dynamic forms:
Analyze how complex you want the form to be generated,. If it simple just generate the form using JSON, if it is complex as you need heavy customizations like including custom functions create the form from a string and generate dynamically.
Creating Form using JSON:
For example create a component that takes a JSON as a prop and generate the form dynamically.
Taking an example component structure of Vuetify Library.
Scope: generate the below form.
The code required to generate the above the form is:
<template>
<v-form v-model="valid">
<v-container>
<v-row>
<v-col
cols="12"
md="4"
>
<v-text-field
v-model="firstname"
:rules="nameRules"
:counter="10"
label="First name"
required
></v-text-field>
</v-col>
<v-col
cols="12"
md="4"
>
<v-text-field
v-model="lastname"
:rules="nameRules"
:counter="10"
label="Last name"
required
></v-text-field>
</v-col>
<v-col
cols="12"
md="4"
>
<v-text-field
v-model="email"
:rules="emailRules"
label="E-mail"
required
></v-text-field>
</v-col>
</v-row>
</v-container>
</v-form>
</template>
<script>
export default {
data: () => ({
valid: false,
firstname: '',
lastname: '',
nameRules: [
v => !!v || 'Name is required',
v => v.length <= 10 || 'Name must be less than 10 characters',
],
email: '',
emailRules: [
v => !!v || 'E-mail is required',
v => /.+@.+/.test(v) || 'E-mail must be valid',
],
}),
}
</script>
Create a component to accept the json as prop
<template>
<v-form v-model="valid">
<v-container>
<v-row>
<v-col
cols="12"
md="4"
v-for="(item, index) in JsonProp"
:key = "index"
>
<v-text-field
v-model="JsonProp.model.item"
:rules="JsonProp.rules.item"
label="JsonProp.label.item"
required
></v-text-field>
</v-col>
</v-row>
</v-container>
</v-form>
</template>
<script>
export default {
prop: ["JsonProp"],
data: () => ({}),
}
</script>
The prop will be like this:
JsonProp: { model: { lastname: "", ...
},
rules: {
lastname:
[
v => !!v || 'Name is required',
v => v.length <= 10 || 'Name must be less than 10 characters',
]
},
label: { lastname: "First name" }
}Creating dynamic form using string will be discussed in my next blog

Comments
Post a Comment