[Vuejs]-How to access nested json object property using nuxtjs and v-for

3πŸ‘

βœ…

You can access nested data using the same . notation you already use to get the first field, so you would need to write something like {{ categories.image.src }}.

<template>
  <ul>
    <li v-for="category in CategoriesData" :key="category.id">
      {{ category.name }}
      <img :src="category.image.src">
    </li>
  </ul>
</template>

Note: You named the variable in your v-for as a plural, while the data it holds is singular. As each item in the list of categories is an individual category.

πŸ‘€user19015424

1πŸ‘

Going to the API itself, located here: http://lavazemesakhteman.com/wp-json/wc/v3/products/categories

Showed that sometimes your image can be null, hence checking for this exception is a nice thing to do

<img v-if="category.image" :src="category.image.src">

Depending on your project and how it’s setup, you could even use Optional Chaining like this

<img :src="category.image?.src">

Otherwise, this uglier form is also available

<img :src="category.image && category.image.src">
πŸ‘€kissu

Leave a comment