0

I'm trying to get the second image url within a JSON object using Vue. I can get the first image src url by specifying <img :src="item.images[0].url" />. So, logically, I thought <img :src="item.images[1].url" /> would get the second image (300x300) variation. It doesn't.

(Update) I just realized I need a v-if because not all playlists have the 300x300 image size.

How do I write if has images[1].url else images[0].url?

My for loop:

<div v-for="(item, index) in $page.oneGraph.spotify.me.playlists" :key="index"> 

Here's what my query returns:

{
  "data": {
    "spotify": {
      "me": {
        "id": "me",
        "playlists": [
          {
            "id": "5EpTRIeVs55Hl1g7NY53v1",
            "name": "Euphrate",
            "images": [
              {
                "url": "https://mosaic.scdn.co/640/ab67616d0000b27320a15cbf156f65c94ef6a506ab67616d0000b27365db2b50dcd76741d9fa12a5ab67616d0000b27377d36619ec51d9f76bb1ffcfab67616d0000b2739d24c92c3d3837eb9366cb79",
                "height": 640,
                "width": 640
              },
              {
                "url": "https://mosaic.scdn.co/300/ab67616d0000b27320a15cbf156f65c94ef6a506ab67616d0000b27365db2b50dcd76741d9fa12a5ab67616d0000b27377d36619ec51d9f76bb1ffcfab67616d0000b2739d24c92c3d3837eb9366cb79",
                "height": 300,
                "width": 300
              },
              {
                "url": "https://mosaic.scdn.co/60/ab67616d0000b27320a15cbf156f65c94ef6a506ab67616d0000b27365db2b50dcd76741d9fa12a5ab67616d0000b27377d36619ec51d9f76bb1ffcfab67616d0000b2739d24c92c3d3837eb9366cb79",
                "height": 60,
                "width": 60
              }
            ],
…
scottrod
  • 477
  • 1
  • 8
  • 21

1 Answers1

0

From the code that you've shared, if <img :src="item.images[0].url" /> works then <img :src="item.images[1].url" /> should work as well.

Most likely what's happening is that one of the playlists in your json only has one image which causes your code to error when you try to access the second image.

To fix this, you could add a v-if like below:

<img :src="item.images[1].url" v-if="item.images.length > 1" />

Shoejep
  • 4,414
  • 4
  • 22
  • 26
  • Yes, it was erroring out because one of the smaller images didn't exist, but the error wasn't specific enough. I figured out an amateurish way of writing it: ` `. I want to say if second image exists, use it, else use the first image. But, there's probably a more efficient way. – scottrod Jul 27 '20 at 20:26
  • You could try `` – Shoejep Jul 27 '20 at 21:32
  • That's better yet. Thanks @shoejep – scottrod Jul 27 '20 at 22:20