Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(image): add "load" event 图片组件添加 “load” 事件 #8006

Closed

Conversation

huangmingfu
Copy link

@huangmingfu huangmingfu commented Jan 11, 2025

onLoad 事件在某些情况下是需要的,比如:

  1. 我需要在图片加载成功之后才显示图片,使用 v-if 控制,在 onLoad 里设置为 true;
  2. 给图片组件的父容器加 loading 效果,在 onLoad 里设置 loading 为 false。
  3. 等等。

(目前4.2.6版本的 a-image@load="onLoad" 事件是不生效的)复现demo

本次修改,移除 watch 监听 img 是因为:

  1. 目前旧的这种是不生效的:
    ant-design-vue/components/vc-image/src/Image.tsx
const img = ref<HTMLImageElement>(null);
watch(
    () => img,
    () => {},
);

应该改为:

watch(
    () => img.value,
    () => {},
);

// or
watch(img,() => {});
  1. 可以减少 watch 监听,而且一般情况下使用 img 标签的 onLoad 事件基本能满足大部分情况。
    如果一定要的话,我会改为下面这种,为了满足 onLoad 的 event 参数:
    (但是会触发两次 emit('load', e) 事件,需要再添加额外判断来实现只触发一次)
const img = ref<HTMLImageElement>(null);
watch(
  () => img.value,
  () => {
    if (status.value !== "loading") return;
    if (
      img.value.complete &&
      (img.value.naturalWidth || img.value.naturalHeight)
    ) {
      const loadEvent = new Event("load");
      Object.defineProperty(loadEvent, "target", {
        value: img.value,
        enumerable: true,
      });
      onLoad(loadEvent);
    }
  }
);

// or
onMounted(() => {
  nextTick(() => {
    if (status.value !== "loading") return;
    if (
      img.value.complete &&
      (img.value.naturalWidth || img.value.naturalHeight)
    ) {
      const loadEvent = new Event("load");
      Object.defineProperty(loadEvent, "target", {
        value: img.value,
        enumerable: true,
      });
      onLoad(loadEvent);
    }
  });
});

Copy link

This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days

@github-actions github-actions bot added the Stale label Mar 14, 2025
@github-actions github-actions bot closed this Mar 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant