Help us understand the problem. What is going on with this article?

vue.js 読み込みできなかったimg画像に代替画像を当てはめる component

More than 1 year has passed since last update.

htmlのimgタグのerrorイベントを利用して、指定した画像がリンク切れなどで読み込みできなかった場合に
指定の代替画像を当てはめるcomponentです。

こんな感じでどうでしょうか。

 Vue.component('replaceableImage', {
    props: ['o'],
    template: '<img :src="o.src" v-on:error="altSrc">',
    methods: {
        altSrc: function()
        {
            this.o.src = this.o.altsrc
        }
    }
})


var vm = new Vue({
    el: '#app',
    data: {
        imgobj: {src:"本来の画像.jpg", altsrc:"代替画像.jpg" }
    }
})
<div id="app">
   <replaceable-image v-bind:o="imgobj"></replaceable-image>
</div>

代替画像の差し込みほか、エラーだった場合のclassを割り当てるなども同じ感じでできそうです。

dskymd
JavaScript, Vue.js, Nuxt.js書いてます。
https://dskymd.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした