How to send data with the fetch post method in VueJS?
February 08, 2023Hi Friends đź‘‹,
Welcome To SortoutCode! ❤️
Today, I am going to show you How do you send data with the fetch post method in VueJS?
Table of Content
- Setup the Vue (Optional)
- Create FirstComponent.vue and import it into App.js
- Send data with the fetch post method
This article will guide you to how do I send data with the fetch post method in vueJS.
Setup the Vue (Optional)
First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation.
How to Install the VueJS project?
Create FirstComponent.vue and import it into App.js
Create the new component in the src/components/
components folder. the component name is FirstComponent.vue
and imported into the App.js
file:
App.js
<template>
<div id="app">
<FirstComponent />
</div>
</template>
<script>
import FirstComponent from "./components/FirstComponent.vue";
export default {
name: "App",
components: {
FirstComponent,
},
};
</script>
Send data with the fetch post method
We are going to call API through the fetch
method and we are using the get
method. we are going to save the API response in the users
data variable. Let’s see the code example:
FirstComponent.js
<template>
<div id="app">
<div style="display: flex; flex-wrap: wrap">
<div v-if="show" class="card">
<div class="card-body">
<h6>
<b>Name: {{ listItems.title }}</b>
</h6>
<p>Email Id: {{ listItems.body }}</p>
</div>
</div>
</div>
<button @click="setData">SetData</button>
</div>
</template>
<script>
export default {
name: "FirstComponent",
data() {
return {
listItems: '',
show:false,
};
},
methods: {
async setData() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts",{
method: 'POST',
body: JSON.stringify({
title: 'Sortout Test',
body: 'welcome to sortout.Have good day!!',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
this.listItems = await res.json();
this.show = true;
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
For now, let’s check the output.

All the best 👍.