引导 Vue 在映像中出现错误事件



如何在 Bootstrap Vue b-card中使用 @onerror 事件?

我想处理图像的 404,以便我可以显示默认图像。

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

我建议在带有no-body道具集的<b-card>内放置一个<b-img-lazy>组件。

<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>

有关上述组件的参考,请参阅:

  • https://bootstrap-vue.js.org/docs/components/card#kitchen-sink-example
  • https://bootstrap-vue.js.org/docs/components/image

好吧,这个组件似乎没有提供这个特定的事件处理程序(在撰写本文时),但你可以在组件上添加一个ref并在mounted钩子上注册错误处理程序:

<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';
    }
  }
});

或者实际上,创建一个包装器组件提供一个。

./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>

索引.html

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

最新更新