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
}
],
…
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" />