Mastering Reusable Forms in Vue.js with vue-form-generator
When building applications, form inputs are the primary source of collecting data from users. As our application grows, we need to reuse forms that capture similar data to avoid creating redundant files. To achieve this, we’ll be utilizing the vue-form-generator package, a schema-based form generator component for Vue.js.
Getting Started with vue-form-generator
vue-form-generator allows us to create reactive forms based on data models or schema. It supports 21 field types, has a built-in form validator, and is highly customizable and extensible. To take this library for a spin, we’ll create a simple user management app that demonstrates how to perform CRUD operations on user records.
Prerequisites
To follow along with this tutorial, you’ll need:
- An IDE of your choice (e.g., Visual Studio Code)
- Node.js (minimum Node v10x) installed on your PC
- Basic understanding of JavaScript and Vue
- Vue CLI installed on your PC
Installation and Setup
First, install the Vue CLI on your PC if you haven’t already. Then, create a new Vue project and install the required dependencies, including vue-form-generator, axios, vue-router, and vue-tel-input.
Building the User Management App
We’ll create a node-express backend to perform CRUD operations. By the end of this tutorial, we’ll have built an application that looks like this:
Configuring Vue Router
Next, we’ll configure the routes for our application by creating a router folder in our src directory. We’ll create the routes for our app and add them to the Vue instance.
Creating the User List View and Creation Form
We’ll create a user list view that displays recorded user details and a create new user button that links to the create users form. Then, we’ll create the user creation form using vue-form-generator, defining the schema, options, model, and tag properties.
Customizing vue-form-generator
We’ll explore how to add custom input types and validation rules to our form fields. We’ll create a custom tel-input field and a strongPassword validation rule.
Implementing the CreateUser Component
We’ll add the user creation page, which contains the create form, and implement the CreateUser component. We’ll use axios to make API calls and vue-form-generator to generate the form fields.
Styling vue-form-generator
Finally, we’ll add custom styles to our form using CSS. We’ll replace the default styling with our own styles to give our form a unique look and feel.
Conclusion
In this article, we’ve learned how to create and manage reusable forms in our Vue application using vue-form-generator. We’ve demonstrated how to generate form components based on their data model, customize form fields, and style the component. The source code for this tutorial is available on GitHub.