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">
<meta charset="UTF-8">
<title>Vue.js | Making API calls using Axios</title>
<body style="text-align: center">
<div style="display: inline-block;margin-top: 100px">
<img src="" alt="">
<h1 style="margin-bottom: 0">John Doe</h1>

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=""></script>
<script src=""></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.

const data = {avatar: "", name: "john doe", email: ""};
var vm = new Vue({
el: '#app',
data: data

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>

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() {
.then(function (response) {
const user =[0];
vm.avatar = user.picture.large; = + " " +; =;

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