AllenC
AllenC

Reputation: 2754

Bootstrap Vue onerror event in image

How can I use the @onerror event in b-card of Bootstrap Vue?

I would like to handle the 404 of image so that I can display a default image.

 <b-card overlay
   :title="name"
   :sub-title="description"
   :img-src="cardImg"
   img-top
   style="max-width: 20rem;"
   class="mb-2">
</b-card>

Upvotes: 1

Views: 3246

Answers (2)

Troy Morehouse
Troy Morehouse

Reputation: 5435

I would recommend placing a <b-img-lazy> component inside of a <b-card> with the no-body prop set.

<b-card no-body>
 <b-img-lazy class="card-img-top" src="...." @error.native="onError" />
 <b-card-body :title="name" :sub-title="description">
   Card Text
 </b-card-body>
</b-card>

For reference on the above components, see:

Upvotes: 4

Yom T.
Yom T.

Reputation: 9190

Well, this component doesn't seem to provide this particular event handler (at the time of writing), but you could add a ref on the component and register the error handler on mounted hook:

<b-card overlay
   :title="name"
   :sub-title="description"
   :img-src="cardImg"
   img-top
   style="max-width: 20rem;"
   class="mb-2"
   ref="card">
</b-card>
new Vue({
  el: '#app',

  mounted() {
    this.$refs.card.querySelector('img').onerror = this.handleImgError;
  },

  methods: {
    handleImgError(evt) {
      // event has all the error info you will need
      // evt.type = 'error';
    }
  }
});

Or actually, create a wrapper component providing one.

./components/Card.vue

<template>
  <b-card
    overlay
    :title="name"
    :sub-title="description"
    :img-src="cardImg"
    img-top
    style="max-width: 20rem;"
    class="mb-2">
  </b-card>
</template>

<script>
import bCard from "bootstrap-vue/es/components/card/card";

export default {
  name: "Card",

  mounted() {
    this.$el.querySelector("img").onerror = e => {
      this.$emit('onerror', e);
    };
  },

  components: {
    bCard
  }
};
</script>

index.html

<div id="app">
  <card @onerror="handleImgError"></card>
</div>

Upvotes: 3

Related Questions