Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an <img> in Vue.js only if the image url exists?

I'm getting a bunch of tweets from the Twitter API. Some tweets have images attached to them, some don't.

Currently, I use this code to display the image of a tweet:

<template lang="jade">
  div Tweet text
    img(:src='tweet.entities.media[0].media_url', width='100%')
</template>

<script>
import store from './store.js';

export default {
  name: 'tweet',
  data () {
    return {
      tweet : store.selectedTweet
    }
  }
}
</script>

The problem is that this only works if the tweet actually has at least one image. If it has no image, I get an exception because tweet.entities.media is undefined.

How can I fix this so that the <img> is only used if there is actually an image available in the tweet's entity value?

like image 248
Timo Ernst Avatar asked Jan 05 '23 19:01

Timo Ernst


2 Answers

You could use v-if:

<template>
    <div class="Tweet text">
        <img :src="tweet.entities.media[0].media_url" width="100%" v-if="tweet.entities.media" />
    </div>
</template>

Using v-if will stop the img element to be rendered.

like image 128
Hammerbot Avatar answered Jan 08 '23 05:01

Hammerbot


In string templates, for example Handlebars, we would write a conditional block like this:

{{#if tweet.entities.media}}
    img(:src='tweet.entities.media[0].media_url', width='100%')
{{/if}}

In Vue, we use the v-if directive to achieve the same:

<template>
    <div class="Tweet text">
        <img :src="tweet.entities.media[0].media_url" width="100%" v-if="tweet.entities.media" />
    </div>
</template>

Here you find the Documentation

like image 43
DomeTune Avatar answered Jan 08 '23 07:01

DomeTune