[Vuejs]-Vue.js โ€“ Filtering inside v-for, how to handle if Array is actually null

1๐Ÿ‘

โœ…

Your v-if should work, but if your condition is more complex than a simple if you can consider using a computed method for this. It could also handle the filter in it. You can also use isArray for a better check.

computed: {
  artistSocialMedia () {
    if( !Array.isArray(this.artwork.artist.socialMedia) ) {
     return []
    }

    return this.artwork.artist.socialMedia.filter(social => social.url.length > 0)
  }
}

and then use the computed method

<a
   v-for="(social, index) in artistSocialMedia"
   v-bind:key="index"
   v-bind:href="parseSocialMediaURL(social.url, social.platform)"
>

</a>

0๐Ÿ‘

As part of the vue documentation, you should not be using them together https://v2.vuejs.org/v2/guide/conditional.html#v-if-with-v-for.

To render conditionally without adding addition elements wrap it in a template

<template v-if="artwork.artist.socialMedia">
    <a
        v-for="(social, index) in artwork.artist.socialMedia.filter(social => social.url.length > 0)"
        v-bind:key="index"
        v-bind:href="parseSocialMediaURL(social.url, social.platform)"
    >
    </a>
</template>

Leave a comment