VueJS: Effettuare chiamate GET in async

In questo breve -brevissimo- articolo vedremo come scrivere in VueJS delle chiamate di tipo HTTP GET in async e mostrare i dati nel client.

Nel seguente esempio scriveremo MyComponent separandolo in due file:

  • MyComponent.vue: conterra’ solamente la parte script
  • MyComponent.vue.html: conterra’ solamente la parte html

MyComponent.vue.html

Come prima cosa potrete vedere nel seguente blocco di codice, andremo a mostrare a video i valori di items se presenti. Allo stesso modo andremo a mostrare eventuali errors ricevuti dalla nostra chiamata verso l’API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<table class="table table-hover"  v-if="items && items.length">
<thead>
  <tr>
    <th scope="col">Field 1</th>
    <th scope="col">Field 2</th>
    <th scope="col">Field 3</th>
    <th scope="col">Field 4</th>
    <th scope="col">Field 5</th>
    <th scope="col">Field 6</th>
    <th scope="col">Field 7</th>
  </tr>
</thead>
<tbody> 
  <tr v-for="i of items" v-bind:key="i">
    <td>{{i.field1}}</td>
    <td>{{i.field2}}</td>
    <td>{{i.field3}}</td>
    <td>{{i.field4}}</td>
    <td>{{i.field5}}</td>
    <td>{{i.field6}}</td>
    <td>{{i.field7}}</td>
  </tr>
</tbody>
</table>

<ul v-if="errors && errors.length">
<li v-for="error of errors" v-bind:key="error">
  {{error.message}}
</li>
</ul>

Se la domanda che vi frulla per la testa e’ come fare ad ottenere items ed errors vi bastera’ leggere la seguente sezione

MyComponent.vue

Nel file di script andremo come prima operazione ad importare axios per poterlo poi utilizzare all’interno del create chiamando il nostro this.apiUrl

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script>
import axios from 'axios';

export default {

  props: {
    apiUrl: String
  },

  data() {
    return {
      items: [],
      errors: []
    }
  },

  async created() {
    try {
      const response = await axios.get(this.apiUrl)
      this.items = response.data
    } catch (e) {
      this.errors.push(e)
    }
  }
}
</script>

Se axios.get ottiene esito positivo, troveremo i valori all’interno di this.items
Se -in caso contrario- axios.get genera errore (ad esempio la mancanza di rete) aggiungeremo l’errore a this.errors

Ora manca l’ultima domanda: In tutto questo apiUrl che valore assume?

App.vue

All’interno de di App.vue quando andremo a chiamare MyComponent aggiungeremo apiUrl in modo da passare il valore a MyComponent.vue

1
2
3
<template>
  <MyComponent apiUrl="http://localhost:7071/api/MyComponentValueGet"/>
</template>

Semplice no?