Introduction
In this article, I will guide how to Make API calls in Vue.js
Prerequisites
- node.js installed
- Basic knowledge of Vue.js
Create Vue.js Project
To create a Vue.js app, use the following command in the terminal.
vue create vueapicall
Now install Bootstrap in the project.
npm install bootstrap
npm install bootstrap-vue
Then, open the main.js
file with your code editor. Import bootstrap.
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Here is the main.js file code.
import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
createApp(App).mount('#app')
Now Install the Axios library using the following command
npm install --save axios
Now right-click on the Src folder > components folder and create a new component named 'Userlist.vue'.and add the following code in this file.
<template>
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Lastname</th>
<th>Phone</th>
<th>Website</th>
</tr>
</thead>
<tbody>
<tr v-for="user in result" :key="user.id">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
<td>{{user.website}}</td>
<!-- <td>Doe</td>
<td>[email protected]</td> -->
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'Userlist',
data() {
return {
result: [],
};
},
props: {
msg: String
},
mounted() {
this.Getemployee();
},
methods: {
Getemployee() {
axios.get('https://jsonplaceholder.typicode.com/users').then(res => {
console.log(res.data);
this.result=res.data;
console.log(this.result);
})
}
}
}
</script>
Now open the App.vue file and add the following code.
<template>
<Userlist/>
</template>
<script>
import Userlist from './components/Userlist.vue'
export default {
name: 'App',
components: {
Userlist
}
}
</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>
Now run the project by using the following command: 'npm run serve'
Summary
In this article, we learned how to make API calls in Vue.js.