简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM