Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Communicates with the Internet Chapter 14

Many a time, the problem is that to leverage this API, we need to trigger the native


validation mechanism. This means that we are not allowed to prevent the default behavior
of the Submit button:


<button type="submit" @click.prevent="vueSubmit">Submit</button>

This will not trigger the native validation and the form will always be submitted. On the
other hand, if we do the following:


<button type="submit" @click="vueSubmit">Submit</button>

The form will get validated but, since we are not preventing the default behavior of the
submit button, the form will be sent to another page, which will destroy the one-page


application experience.


The trick is to intercept the submit at form level:


<form @submit.prevent="vueSubmit">

This way, we can have form native validation and all the modern browsing experience we


really like.


Creating a form and sending data to your server


HTML forms are a standard way to interact with your user. You can gather their data to


register within the site, make them log in, or even carry out more advanced interactions. In
this recipe, you will build your first form with Vue.


Getting ready


This recipe is very easy, but it assumes that you already know about AJAX and you want to


apply your knowledge on Vue.


How to do it...


Let's pretend that we have a blog, and we want to write a new post. For that, we need a
form. Here is how you lay out the HTML:


<div id="app">
Free download pdf