LoginSignup
6

More than 3 years have passed since last update.

posted at

updated at

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

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を割り当てるなども同じ感じでできそうです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
6