Learn html, css, javascript online and how to make a webpage design

How to use axios get API data and render data in VueJS?

Sunday 3rd of January 2021 06:07:22 PMaxiosvuejs

Currently, almost all applications operate on data obtained from the API Gateway. One of the complexes we can use to interact with the API to get data from the server is axios. So how to use axios in VueJS application.

For example, we have an API portal at the address https://htmlcssdownload.com/api/categories returns data in json format and has the following structure. The API Gateway only returns data in the GET method.

JSON data from API Gateway looks like below:

 

[
   {
      "id": 1,
      "name": "Javascript"
   },
   {
      "id": 2,
      "name": "HTML CSS"
   },
   {
      "id": 3,
      "name": "VueJS"
   }
]

 

Use axios in the VueJS application to get data from the API Gateway

<!DOCTYPE html>
<html>
<head>
    <title>How to use axios get API data and render data in VueJS? - HtmlcssDownload.com</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
</head>
<body>
    
<div id="app">
    <ul>
       <li v-for="(item, index) in categories">{{ index }}. {{ item.name }}</li>
    </ul>
    <button @click.stop.prevent="loadData()">Load data</button>
</div>
   
<script type="text/javascript">
 
    var app = new Vue({
      el: '#app',
      data: {
         categories: []
      },
      methods:{
         loadData: function(){
            let APIGateway = 'https://htmlcssdownload.com/api/categories';
            let vm = this;
            axios.get(APIGateway).then(function(res){
               vm.categories = res.data;
            })
         }
      }
    })
    
</script>
    
</body>
</html>

 

We are Recommending you: