图片加载失败重试,重试至预期次数使用占位图

支持自定义重试次数,支持重试回调,支持重试使用备用域名。 这里使用自定义指令做了封装,可读性MAX!!!

运行截图 调用方式

ini 复制代码
    <img
      v-useReload="{
        src: 'https://user-images.githubusercontent.com/10731096/95823103-9ce15780-0d5f-11eb-8010-1bd1b5910d4f.png',
        callback: (e, count) => {
          console.log('重试次数:', count, e);
        },
      }"
      src="https://user-images.githubusercontent.com/10731096/95823103-9ce15780-0d5f-11eb-8010-1bd1b5910d4f2.png"
    />
    <img
      v-useReload="reload"
      src="https://user-images.githubusercontent.com/10731096/95823103-9ce15780-0d5f-11eb-8010-1bd1b5910d4f2.png"
    />

话不多说直接上代码

ini 复制代码
/**
 * Description
 * 方式一:<DOM v-useReload />
 * 方式二:<DOM v-useReload="{errorImg,maxRetries,src,callback}" />
 * 方式三:<DOM v-useReload="callback" />
 * @author ZHYCH
 * @date 2024-12-27
 * @param {any} el:HTMLElement
 * @param {any} binding:DirectiveBinding<option>
 * @returns {any}
 */
import { DirectiveBinding } from 'vue';
import errorimg from '@/assets/imgerror.svg';

type callback = (retryCount: number) => void;

interface option {
  errorSrc?: string; //失败地址
  maxRetries?: number; // 最大重试次数
  src?: string; //备用地址
  callback?: callback; //失败回调
}

export default {
  beforeMount(el: HTMLElement, binding: DirectiveBinding<option | null | callback>) {
    const { value } = binding;
    const isObject = typeof value === 'object' && value !== null;

    const maxRetries = value?.maxRetries ?? 3;
    const src = value?.src ?? el.src;
    const errorSrc = value?.errorImg ?? errorimg;
    const callback = isObject ? value?.callback : value;

    let retryCount = 0; // 当前重试次数

    const reloadImage = () => {
      if (retryCount < maxRetries) {
        retryCount++;
        el.src = '';

        setTimeout(() => {
          callback?.(el, retryCount);
          el.src = src;
        }, 0);
      } else {
        el.src = errorSrc;
      }
    };

    el.addEventListener('error', reloadImage);

    // 清理事件监听器
    el._reloadImage = reloadImage;
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener('error', el._reloadImage);
  },
};
相关推荐
xiaofeichaichai6 小时前
Webpack
前端·webpack·node.js
问心无愧05136 小时前
ctf show web入门111
android·前端·笔记
唐某人丶6 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界6 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌7 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel8 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3118 小时前
https连接传输流程
前端·面试
徐小夕8 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
梦梦代码精8 小时前
2026年PHP开源商城系统实测对比:架构、多商户、商用授权,谁才是真·省心?
vue.js·docker·架构·开源·代码规范