How to display async data in vue template

I always use a loader or a spinner when data is loading!

<template>
  <table>
    <thead>
      <tr>
        <th>One</th>
        <th>Two</th>
        <th>Three</th>
      </tr>
    </thead>
    <tbody>

      <template v-if="loading">
        <spinner></spinner> <!-- here use a loaded you prefer -->
      </template>

      <template v-else>
        <tr v-for="row in rows">
          <td>{{ row.name }}</td>
          <td>{{ row.lastName }}</td>
        </tr>
      </template>

    </tbody>
  </table>
</template>

And the script:

<script>
  import axios from 'axios'
  export default {
    data() {
      return {
        loading: false,
        rows: []
      }
    },
    created() {
      this.getDataFromApi()
    },
    methods: {
      getDataFromApi() {
        this.loading = true
        axios.get('/youApiUrl')
        .then(response => {
          this.loading = false
          this.rows = response.data
        })
        .catch(error => {
          this.loading = false
          console.log(error)
        })
      }
    }
  }
</script>

Leave a Comment