[Vuejs]-Can't access a property in an array of objects

1👍

You should never trust the data from another place like a remote server

The code is pretty easy to be broken by invalid data, such as null product, null images, image without the path. So in the actual practice of play with the data, it very much recommended to add the type and value check to ensure the accessing is always safe.

As in Vuejs, it’s pretty easy to achieve that by using v-if, only render the piece of template when the preserved data(product,images,image) is provided as expected. This is called as ‘Defensive Programming’.

0👍

try if this works

    data: function () {
      return {
        product: {
          name:'',
          images:[]
        },
        quantity: 1
      }
    },
👤waiaan

0👍

Try defining a new property images: [] and use that for the loop instead of image in product.images.
For example, change in your code like:

<vue-glide :per-view="1">
  <vue-glide-slide v-for="image in images">
    <div class="h-100 bg-red-500">
      <img :src="/images/ + image.path" alt="">
    </div>
  </vue-glide-slide>
</vue-glide>
data () {
  return {
    product: null,
    images: [],
    quantity: 1
  }
},
mounted() {
  axios.get('/api/products/' + this.$route.params.id)
    .then(response => {
      this.product = response.data.data;
      if (response.data.data.images) {
        // Check if images exist in response.data.data
        this.images = response.data.data.images
      }
    })
    .catch(error => {
      alert('Unable to fetch product.')
    });
}

Leave a comment