9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-07-02

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

9
6
0

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
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?