Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vue

How to create a form in Vue.js

Shubham Singh Kshatriya

Overview

A form is generally used to allow a user to enter data that is sent to the server for some processing or storing in the database.

In this shot, we'll learn to create a form in Vue.js.

Code example

We'll create a simple registration form, which will contain the following elements:

  • An input field to enter the name
  • An input field to enter the email
  • The radio buttons to select gender
  • A button to submit the form

Let's start with the code:

import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
}).$mount('#app')

Code explanation

In the file Form.vue:

Inside the <template></template> tags:

  • Line 3: We create a form and attach the submitForm() method on its submit event. We add a v-if on this form to hide its content when formSubmitted is false.
  • Lines 4 to 9: We create an input element that allows users to enter their names.
  • Lines 10 to 15: We create another input element that allows users to enter their email.
  • Lines 16 to 28: We create two radio button elements that allow users to enter their gender.
  • Lines 29 to 33: We create a form submit button.
  • Lines 35 to 41: We create a div element that shows the form input data when the form gets submitted. We add a v-if on this div to show its content when formSubmitted is true.

Note: We have created a two-way binding on all the form input elements, using the v-model attribute. It is mainly used to sync the form input elements in the frontend with the corresponding states in JavaScript.

Inside the <script></script> tags:

  • Lines 46 to 53: We create the required properties that are used in the form inside the data() function.
  • Lines 55 to 57: We create a submitForm() method that is invoked when the form is submitted.

Inside the <style></style> tags:

  • Lines 62 to 88: We add some CSS to format our UI.

Output

In the output, we see a form that contains an input field for full name and email, a radio button to select gender, and a submit button.

When the form is submitted, the submitForm() method is invoked, and the Boolean formSubmitted is set to true. Therefore, the form is hidden due to the conditional rendering set by v-if and the div with the input data shown.

RELATED TAGS

vue

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring