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?
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. 
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With