Building Forms with Vue.js
eBook - ePub

Building Forms with Vue.js

Patterns for building and scaling complex forms with great UX

  1. 108 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Building Forms with Vue.js

Patterns for building and scaling complex forms with great UX

About this book

Learn how to build dynamic schema-driven forms with Vue from scratch

Key Features

  • Understand the basics of form component composition
  • Scale and integrate your forms with libraries such as Vuex and Vuelidate
  • Convert any form into a self-generated schema-driven app

Book Description

Almost every web application and site out there handles user input in one way or another, from registration forms and log-in handling to registration and landing pages. Building Forms with Vue.js follows a step-by-step approach to help you create an efficient user interface (UI) and seamless user experience (UX) by building quick and easy-to-use forms.

You'll get off to a steady start by setting up the demo project. Next, you'll get to grips with component composition from creating reusable form components through to implementing the custom input components. To further help you develop a convenient user input experience, the book will show you how to enhance custom inputs with v-mask. As you progress, you'll get up to speed with using Vuelidate and Vuex to effectively integrate your forms. You'll learn how to create forms that use global state, reactive instant user input validation and input masking, along with ensuring that they are completely schema-driven and connected to your application's API. Every chapter builds on the concepts learned in the previous chapter, while also allowing you to skip ahead to the topics you're most interested in.

By the end of this book, you will have gained the skills you need to transform even the simplest form into a crafted user and developer experience with Vue.

What you will learn

  • Learn all about the basics of creating reusable form components with the Vue framework
  • Understand v-model and how it plays a role in form creation
  • Create forms that are completely powered and generated by a schema, either locally or from an API endpoint
  • Understand how Vuelidate allows for easy declarative validation of all your form's inputs with Vue's reactivity system
  • Connect your application with a Vuex-powered global state management
  • Use the v-mask library to enhance your inputs and improve user experience (UX)

Who this book is for

If you are a developer with basic Vue experience who wants to enhance your forms, then this book is for you. No previous experience with any of the libraries used in the book is required.

Trusted by 375,005 students

Access to over 1.5 million titles for a fair monthly price.

Study more efficiently using our study tools.

Information

Year
2019
Print ISBN
9781839213335
eBook ISBN
9781839211515
Edition
1
Topic
Design

Creating Schema-Driven Forms

Forms come in different shapes, sizes, and levels of complexity. It is relatively simple to quickly scaffold a login form or a contact form with a few fields, but what happens when you have to take it to the next level and create a completely dynamic form that is driven by an API or schema?
Up until now, we have worked with a relatively simple form that only asks the user for some basic data but everything is hardcoded as a static form. If our mock website wanted to add or remove some fields from the form, we would have to manually make the changes, deploy them to our server, and possibly even adjust the backend to handle the different fields. But what if we wanted to automate this whole process?
In this chapter, we will build an example dynamic form that will be completely powered by an API endpoint. Schema-driven forms are very powerful, as they can be controlled and modified directly by your application's API. That means when something changes in your backend, your form will automatically adjust itself not only on the frontend but also into a self-aware understanding of how to send the dynamic data back to the API.
This chapter will cover the following topics:
  • Exploring the starter kit
  • Preparing the schema
  • Loading the schema and creating a Renderer component
  • Dynamically binding user data
  • Creating a mock API
  • Loading the new API into the app
  • Translating the API into a working schema

Technical requirements

I will assume that you have either read or understand the concepts viewed in the previous chapters, such as using Axios for HTTP calls and component creation, and have installed on your system as a mock API provider. You can refer to this link for more information: https://mockoon.com/.
To expedite the scaffolding of our app, I have set us up with a starter Vue CLI-3-powered repository with a couple of custom components and a sample static form. You can clone or download it from the following link:
https://github.com/PacktPublishing/Building-Forms-with-Vue.js/tree/master/Chapter07.
Check out the following video to see the code in action:
http://bit.ly/2VMe3eU

Exploring the starter kit

After you clone or download the starter repository, you will find yourself with a Vue CLI 3 project. The first thing to do is to take a look at what we are going to be working with! The repository contains a very simple form with some input fields and a select box. You can find the structure for the form in App.vue. As you can see, we are using two different custom components, BaseInput and BaseSelect. Both of these can be found inside the src/components folder. They both wrap an input and select tag, respectively, and expose some properties that we can use to inject the necessary data into each of them, such as labels and options.
I have taken the liberty of already adding Axios to the project dependencies; you can check out package.json to corroborate. Bootstrap's CSS file for some base classes has been imported inside main.js.
Now that we have a good overview of the project structure, let's go ahead and install the dependencies and run them on our browser. Follow these steps:
  1. Go into the Terminal and run the following commands:
 > npm install
> npm run serve
  1. After doing this, check out the form on your browser and play around with the fields. There's nothing fancy going on except for the fields being v-model bound to the local state in App.vue.
The Submit button will only log a message to the consoleif you want a refresher on how to send form data to your server, check out Chapter 2, A Form in its Simplest Form, of this book.
Now that you have an understanding of the starting point of our application, we are going to prepare the demo schema in the next section.

Preparing the schema

Currently, our form (as previously stated) is hardcoded. The first step that is required to start making it a dynamic form is to remove the need to add BaseInput or BaseSelect directly to our App.vue file every time we need to add a new field. This implies that we are going to need to have some sort of organized structure, or schema, to represent what we are trying to accomplish for our form. Since we are using JavaScript, the most logical way to do this is with a JSON object format. This will make it easier later on when we want to take it a step further and have our mock API feed the information directly to our form.
For now, we will use a static schema. Let's create a data folder inside src, and inside of it, make a new schema.json file. We are going to populate our JSON file with some dummy data. I have chosen, for the sake of an example, to make the top element an object, and each property inside of it will represent one of the fields in our form. Each element will consist of at least a component property and a label property. In the case of drop-down menus, however, we will also include options to populate it.
To create the demo schema, add the following data to schema.json:
 { "firstName": { 
"component": "BaseInput",
"label": "First name"
},
"lastName": {
"component": "BaseInput",
"label": "Last name"
},
"favoriteAnimal": {
"component": "BaseSelect",
"label": "What's your favorite animal?",
"options": [
{ "label": "Cat", "value": "cat" },
{ "label": "Dog", "value": "dog" },
{ "label": "Sea Otter", "value": "onlyvalidanswer" }
]
}
}
Now that we have a structured schema as a demo of what we want our dynamic form to understand, we can proceed to the next section—where we will load this schema into our application with the help of a Renderer component.

Loading the schema and creating a Renderer component

Now that we have a basic schema set up to work with, let's go ahead and load into the application so that we can use it. Later on in this chapter, we are going to create a dummy API that will feed us the data in a slightly different way, and we will transform it on our end to fit our app's requirements.
For now, let's go to App.vue and import the JSON. We will start by adding the following import statement to the top near the other import statements:
import schema from '@/data/schema.json';
Now that we have our data available to our application, we need some components to be able to parse this information into the BaseInput and BaseSelect components. Let's go ahead and create a new file inside the components folder, and name it Renderer.vue. This component will have a single purpose: to understand our schema and render the correct component to the screen. It will currently have a single property, element, which represents each of the elements in our schema. To do so, add the following code to Renderer.vue:
 <template>
<component
:is="component"
v-bind="props"
/>
</template>
<script>
export default {
props: {
element: {
type: Object,
required: true
}
},
computed: {
component() {
const componentName = this.element.component;
return () => import(`./${componentName}`);
},
props() {
return this.element;
}
}
}
</script>
There's a couple of important things to note in this component. They are as follows:
  • The element prop is an object and will be required. This component will not work at all without it. We have two computed properties. The first component takes care of dynamically loading whichever element we need. First, we create a componentName constant and assign it to the value of element.component, which is where the string name of our component is stored in the schema.
  • It's important to mention that we are not just adding this const for clarity purposes. The way that computed properties work regarding caching requires that this const exists here since we are returning a function, which will not be inspected for dependencies.
  • When this computed property is called by the <component> tag for the : is an attribute—it will load the component and pass it over. Note that this will only work if the component is globally registered; in any other case, a computed property that requires the correct component would be needed. For further information on dynamic components, check out the official documentation: https://vuejs.org/v2/guide/components-dynamic-async.html.
The second computed property, props, will simply pass down the whole element with its properties as props to whatever component we are loading using the v-on binding. For example, on the BaseSelect component, it will pass down the options property in our schema to the component so that it can render the correct options. If you are wondering why we are using a computed property instead of just passing the element directly to the v-on directive, you are on the right track. Right now, it is definitely not needed, but having it set up in this way to begin with allows us to, later on, add another level of logic or parsing that could be needed for a particular component.
Let's head back to App.vue.
We need to import our Renderer component and add it to the template. We also need to clean ...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. About Packt
  5. Foreword
  6. Contributors
  7. Preface
  8. Setting up the Demo Project
  9. A Form in its Simplest Form
  10. Creating Reusable Form Components
  11. Input Masks with v-mask
  12. Input Validation with Vuelidate
  13. Moving to a Global State with Vuex
  14. Creating Schema-Driven Forms
  15. Other Books You May Enjoy

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.5M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1.5 million books across 990+ topics, we’ve got you covered! Learn about our mission
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access Building Forms with Vue.js by Marina Mosti in PDF and/or ePUB format, as well as other popular books in Design & Digital Marketing. We have over 1.5 million books available in our catalogue for you to explore.