Vue 图片加载失败处理

Vue 图片加载失败处理

很多人会使用 @error 方法在图片加载 失败时替换img.src 的方式

但是这种方式在默认图片加载失败时,@error会出现死循环,所以我使用了@error + v-if的方式。

<template>
  <div>
    
    <img v-if="!imgError" :src="imgUrl" @error="imgErrorHandler"/>
    
    <img v-else :src="defaultImgUrl"/>
  div>
template>
  export default {
    name: 'ImgOnError',
    data() {
      return {
        imgError: false,
        imgUrl: 'https://images.unsplash.com/photo1-1706733144563-c42ec7e637' +
          'd4?q=80&w=870&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fD' +
          'B8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',
        defaultImgUrl: 'https://images.unsplash.com/photo-1706508963745-d090f' +
          '82a0416?q=80&w=435&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxM' +
          'jA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'
      }
    },
    methods: {
      imgErrorHandler() {
        // 图片加载失败时调用,用于替换为显示默认图片
        this.imgError = true;
      }
    }
  }

使用这种方式在默认图片也加载失败时会死循环

在看了很多文章后,发现大多是在 @error 方法中添加 img.onerror = null,目的是为了防止默认图片也加载失败时 @error 一直循环调用,但是在我的测试中,这个语句并不能防止这个问题,不知道是版本还是什么原因。

<template>
  <div>
    <img :src="imgUrl" @error="imgErrorHandler"/>
  div>
template>
  export default {
    name: 'ImgOnError',
    data() {
      return {
        imgUrl: 'https://images.unsplash.com/photo1-1706733144563-c42ec7e637' +
          'd4?q=80&w=870&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fD' +
          'B8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',
        defaultImgUrl: 'https://images.unsplash.com/photo-1706508963745-d090f' +
          '82a0416?q=80&w=435&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxM' +
          'jA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'
      }
    },
    methods: {
      imgErrorHandler(event) {
        let img = event.srcElement;
        img.src = this.defaultImgUrl;
        // 很多文章在这里写上这句,为了防止error方法循环调用
        // 但是我在测试时并不生效
        img.onerror = null;
      }
    }
  }

你可能感兴趣的:(vue,前端,vue.js,javascript,前端)