Home » vue » How do I use v-if statement to show static image in vuejs

How do I use v-if statement to show static image in vuejs

Posted by: admin November 26, 2021 Leave a comment


I want to show a static image if no image is uploaded in vuejs.


<img :src="sub_section.imageURL ? sub_section.imageURL: '@/assets/images/upload.png'"  alt="">

but it is not working. how do I go about it?


If you want to use v-if specifically then you don’t need to use ternary operator. You can try this way to show default image using v-if and v-else.

<img v-if="sub_section && sub_section.imageURL" :src="sub_section.imageURL" alt="uploaded-image">
<img v-else src="@/assets/images/upload.png"  alt="default-image">

Here, in the above code, if you get something in sub_section and imageURL both then v-if block will be executed, or else default image will be shown by executing v-else block.

You need to make sure that you apply condition for both sub_section and imageURL because there’s a possibility that you might not get anything in the first variable sub_section itself, which might throw an error if you would be directly using sub_section.imageURL in the condition.


try this

<img :src="sub_section.imageURL ? require(sub_section.imageURL): require('@/assets/images/upload.png')"  alt="">


Import the image first in the: data.

    return {
        defaultImage: require('@/assets/images/upload.png')

In the component:

<img :src="sub_section.imageURL ? sub_section.imageURL: defaultImage" >