Vue.js | Making API calls using Axios

Dhiraj Sharma

Basic example to make network requests in VueJS using Axios.

In this post we will use free API Random User Generator to demonstrate network request in VueJS using Axios.

First lets create a html file and put following code :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue.js | Making API calls using Axios</title>
</head>
<body style="text-align: center">
<div style="display: inline-block;margin-top: 100px">
<img src="https://ui-avatars.com/api/?size=128" alt="">
<h1 style="margin-bottom: 0">John Doe</h1>
<span>johndoe@email.com</span>
</div>
</body>
</html>

As we can see its just plain html code with static image,name & email, now we will use Vue to set those info.

To do that, first lets include VueJS & Axios. Put following script at end of body.

....................
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Now instead of writing raw values in html, lets create an data variable(with default values for now) and set created data to VueJS instance.

.................
<script>
const data = {avatar: "https://ui-avatars.com/api/?size=128", name: "john doe", email: "johndoe@email.com"};
var vm = new Vue({
el: '#app',
data: data
});
</script>

Now lets update our html (inside body)

<div id="app" style="display: inline-block;margin-top: 100px">
<img v-bind:src="avatar" alt="">
<h1 style="margin-bottom: 0">{{name}}</h1>
<span>{{email}}</span>
</div>

Changes here:

  • div has id app which is used as el above while creating Vue instance.
  • v-bind is used to set src for image
  • Double curly braces is used to display variable data for name & email.

Now here comes the main part, we will make an api call & update content of data. (which will automatically update our UI due to reactivity.)

Put following code inside Vue instance (below data)

..............,
mounted() {
axios.get('https://randomuser.me/api/')
.then(function (response) {
const user = response.data.results[0];
vm.avatar = user.picture.large;
vm.name = user.name.first + " " + user.name.last;
vm.email = user.email;
})
}

What above code does is, call api using axios once Vue instance is mounted. (More on Instance Lifecycle Hooks)

We are done !

Now every time you reload the page, you can see new user with placeholder at start.

Get final code here.

Thanks for reading !
Dhiraj Sharma

Dhiraj Sharma

Written by

Developer Android, Flutter

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade