Forms and model in Vuejs


We have seen some of the basic operations in vuejs . Now move on to advanced area. In the following example we will learn how to process a form in Vue

We have a simple form component with two controls which has indeed three section template, Script and a Style.

    <template>
.........
<form @submit.prevent="createContent">
 <label for="newContent">
          <textarea            
            placeholder="content here"
            id="newContent"
            rows="7"
            v-model="newContent"
          />
<Button > Save</button>
</template>

We have a very simple form with one text area and a button to save. I removed the styling elements for simplicity.

Bind the textarea

To bind the textarea we have to use v-model directive of vue , so that we can access the value.

v-model="newContent"

Event handling

In the form tag , we can specify a event handler for the button click. To use a method as event handler for submit we can use @sumit=”<method>”, for a click event we have to use @click=”methodName”.

We also need to prevent the default form submission event which occurs when the use press enter key in the input field. For that we used submit.prevent

The Script

Everything behind the scene belongs to the script. Here we have to create the

  • property for binding model
  • method for event handling
<script> 
export default { 
  name: "Form",
  created() {},
  data() {
  newContent= ''
  },
  methods: {
    createContent() {
      if (this.newContent) {
        //code to handle the event

        // clear the field after sibmission
        this.newContent = ''
      }
    },
  },
}
}

Now you know how to handle forms in vue, simple isn’t it ?

The following vue post posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.