Search code examples
vue.jsvuejs2vue-component

How to wait until data is loaded for showing this v-if condition correctly in Vue.js?


It shows the no items found before the data is getting loaded., code looks like this:

<div class="columns" v-if="!products.length">
<p>No items found</p>
</div>
<div class="columns" v-if="products.length">
</div>

    async getProducts() {
      let res = await api.products.getProducts({
        products: products
      })
    },

Currently, it shows that no items found until the data is loading. How can I show that message only when data is loaded and it's empty?


Solution

  • You can have a variable this.loading = false and toggle after loaded.

    data() {
      return { loaded = false }
    },
    methods: {
      async getProducts() {
        let res = await api.products.getProducts({
          products: products
        });
        this.loaded = true;
      },
    }
    

    In template.

    <div class="columns" v-if="loaded && !products.length">
      <p>No items found</p>
    </div>
    <div class="columns" v-if="loaded && products.length"></div>