【问题标题】:Vuejs change background image url, if image not existVuejs更改背景图片网址,如果图片不存在
【发布时间】:2019-01-31 16:07:53
【问题描述】:

我有一个简单的 v-for 循环。在里面我有一个带有样式背景img的div。如果我的图片不存在,如何设置默认背景图片 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'

【问题讨论】:

  • 不存在的意思是,company.code 字段未定义或一切正常,只是 url 无法加载。
  • url加载失败

标签: css vue.js background-image


【解决方案1】:

您需要@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'     
      }
    }
} 

更新:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 2012-10-16
      相关资源
      最近更新 更多