Vuejs 更改背景图像 url,如果图像不存在

Vuejs change background image url, if image not exist

我有一个简单的 v-for 循环。在里面我有一个 div 样式背景 img。如果我的图片不存在

,我该如何设置默认背景图片 url
<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>

如果公司图片不存在我想设置背景图片:url(/static/img/companies/default.png'

通常,这种类型的操作留给服务器,因为客户端不知道远程文件是否存在。

想到的一个可能的解决方案是,当您构建页面时,调用服务器以检索有关公司的信息,包括图像的 URL。然后您可以使用该结果来填充背景图像样式。

您将需要 @error vue 事件,它基本上是 javascript onerror,可用于在给定图像 url 失败时加载备用图像。

<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>

内部方法,

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

Update:

如果 country.code 对象不存在,则将 :src 更改为

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