[Vuejs]-Checking if something exists in json in Vue

0👍

What about a v-if & v-else condition on the length of the stocks array? If the length is greater than zero we have stocks, so display them, else, display a message. Something like this.

Vue.component('your-component', {
   template:
   `
   <div v-for="(item, i) in items" :key="i">
      <p>{{ item.name }}<p>
      <p>{{ item.id }}<p>

      <div v-if="item.stock && item.stock.length > 0">
         <p v-for="(stock, j) in item.stock" :key="j">
            There'are {{ stock.count }} of size {{ stock.size }}.
         <p>
      </div>
      <div v-else>
         Ops... stocks not available.
      </div>
   </div>
   `,
   data () {
      return {
         items: []
      }
   },
   created () {
      fetch('your-api')
         .then((res) => res.json())
         .then((res) => { this.items = res })
   }
})

Leave a comment