[Vuejs]-Dynamic / Async Component Render

0๐Ÿ‘

A common pattern would be to have the first render be without data, then re-render whenever your data comes in. The browser will make sure that not too many network requests run at the same time, so you should not have lag perse from that. You just perceive lag, because your component does not render until the data loads.

I would suggest using something like Axios, which uses promises and makes it easy to create asynchronous http requests while still keeping your code readable.

<template>
  <div class="widget graph">
    <div v-if="loading">
      <span>Loading...</span>
      <img src="assets/loader.svg">
    </div>
    <div v-else>
      <!-- Do whatever you need to do whenever data loads in -->
    </div>
  </div>
</template>

<script>
export default {
  name: 'WidgetGraph',

  data () {
    return {
      loading: true,
      error: null,
      graphData: {}
    }
  },

  created () {
    this.loadData();
  },

  methods: {
    loadData () {
      return axios.get(...).then((data) => {
        this.loading = false;
      }).catch(() => {
        this.error = 'Something went wrong.... Panic!';
        this.loading = false;
      });
    }
  }
}
</script>

<style>

</style>
๐Ÿ‘คSumurai8

Leave a comment