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?
Advertisement
Answer
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.