Vuejs 2绑定图像src [英] Vuejs 2 bind image src

查看:111
本文介绍了Vuejs 2绑定图像src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多行的表格和< td> 使用Vuetify加载动态网址图片

I have a table with multiple rows and a <td> loading a dynamic url image using Vuetify

<v-data-table :headers="headers" :items="items">
  <template slot="items" scope="props">
      <td>
         <img :src="getImgUrl(props.item.styleCode)" />
      </td>
  </template>
</v-data-table>

然后

checkImage(imageSrc, good, bad) {
   let img = new Image();
   img.onload = good;
   img.onerror = bad;
   img.src = imageSrc;
},
getImgUrl(styleCode) {
  var image = 'http://192.168.1.19/Images/ClassImages/' + styleCode + '.png';

  this.checkImage(image,
  function () {
     return 'http://192.168.1.19/Images/ClassImages/' + styleCode + '.png';
  }, function () {
     return 'http://192.168.1.19/Images/ClassImages/default.png';
  });
}

此返回任何内容。
我做得不好?

This return nothing. What are I doing bad?

编辑:这是加载外部图像,如果不存在则加载默认图像

This is to load an external image and if doesn't exist load a default image

推荐答案

你没有在 getImgUrl 方法中返回任何内容,这意味着你没有绑定 src 属于任何东西。

You're not returning anything in the getImgUrl method, meaning you're not binding the src attribute to anything.

尝试设置src然后使用<更简单code> @error 直接在 img 元素上的侦听器来处理加载失败的事件:

It'd be much simpler to attempt to set the src and then use an @error listener directly on the img element to handler the event of a failed load:

new Vue({
  el: '#app',
  methods: {
    getImgUrl(i) {
      if (i === 4) {
      	return 'http://thisonewontwork';
      }
      return 'http://placehold.it/120x120&text=image' + i;
    },
    onError(e) {
      let defaultURL = 'http://placehold.it/120x120&text=default';
      if (e.target.src !== defaultURL) {
        e.target.src = defaultURL;
      }
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <template v-for="i in 4">
    <img :src="getImgUrl(i)" @error="onError">  
  </template>
</div>

这篇关于Vuejs 2绑定图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆