Vue Communicates with the Internet Chapter 14
<h3>Write a new post</h3>
<form>
<div>
<label>Title of your post:</label>
<input type="text" v-model="title">
</div>
<div>
<label>Write your thoughts for the day</label>
<textarea v-model="body"></textarea>
</div>
<div>
<button @click.prevent="submit">Submit</button>
</div>
</form>
</div>
We have a box for the title, one for the body of our new post, and a button to send our post.
In our Vue instance, those three things along with a user ID will be part of the state of the
app:
new Vue({
el: '#app',
data: {
userId: 1,
title: '',
body: ''
}
})
At this point, we just need to add a method to send the data to our server when we click on
the Submit button. Since we don't have a server, we will use a very useful service by
Typicode. It's basically a fake REST server. We will send a request and the server will
respond in a realistic manner, even if nothing will really happen.
Here's our method:
methods: {
submit () {
const xhr = new XMLHttpRequest()
xhr.open('post', 'https://jsonplaceholder.typicode.com/posts')
xhr.setRequestHeader('Content-Type',
'application/json;charset=UTF-8')
xhr.onreadystatechange = () => {
const DONE = 4
const CREATED = 201
if (xhr.readyState === DONE) {
if (xhr.status === CREATED) {