mtleppay
mtleppay

Reputation: 281

Vuejs change background image url, if image not exist

I have a simple v-for loop. Inside i have a div with style background img. How can i set a default background image url, if my image doesn't exist

<div v-for="company in companies">
    <div class="company-img tooltip-target b-link" 
        :style="{ 'background-image': 'url(' + '/src/static/img/companies/' + 
        company.code.toLowerCase() + '.png' + ')' }">
    </div>
</div>

If company image doesn't exist i want to set backgroudn-image : url(/static/img/companies/default.png'

Upvotes: 1

Views: 3705

Answers (2)

Helping hand
Helping hand

Reputation: 2920

You would need @error vue event which is basically javascript onerror that can be used to load alternate image when given image url fails.

<div v-for="company in companies">
    <div class="company-img tooltip-target b-link" >
      <img  @error="onImageLoadFailure($event)" :src="'/src/static/img/companies/' + company.code.toLowerCase() + '.png'" />
    </div>
</div>

Inside method,

export default {
    methods: {
      onImageLoadFailure (event) {
        event.target.src = '/static/img/companies/default.png'     
      }
    }
} 

Update:

Incase the country.code object is not present then change :src to,

:src="'/src/static/img/companies/' + company.code.toLowerCase() + '.png'|| '' "

Upvotes: 8

TheVirtuoid
TheVirtuoid

Reputation: 100

Normally, this type of operation is left to the server, as a client will not know if a remote file exists or not.

One possible solution that comes to mind is that when you build your page, make a call to the server to retrieve information about the companies, including URLs for images. Your can then use that result to fill in the background image style.

Upvotes: -2

Related Questions