简体   繁体   中英

Getting error "Cannot read property 'url' of undefined" when data is present

I keep getting this error from a tag when attempting to render a component which looks like this:

<template>
  <div v-if="playlists" class="playlists">
      <router-link
        :to="`/playlist/${playlist.id}`"
        tag="div"
        v-for="playlist in playlists"
        :key="playlist.id"
        class="playlist"
      >
        <img :src="playlist.images[0].url" alt="bild">
        <h2>{{playlist.name.toUpperCase()}}</h2>
      </router-link>
  </div>
</template>

<script>
export default {
  data() {
    return {
      playlists: null
    };
  },
  beforeMount: function() {
    if (this.$parent.$parent.loggedIn) {
      this.spotify.getUserPlaylists().then(data => {
        this.playlists = data.body.items;
      });
    }
  }
};
</script>

All the data is present and I can render out the playlist.images[0] object but when attempting to render playlist.images[0].url it gives me the error. The image array looks like this:

"images": [
        {
            "height": null,
            "url": "www.example.com",
            "width": null
        }
 ]

How can I solve this?

Render <img> when playlist is updated with API response:

change

<img :src="playlist.images[0].url" alt="bild"> 

to

<img v-if="playlist.images.length > 0" :src="playlist.images[0].url" alt="bild">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM