fix(components): [el-image] image load error (#4820)

Co-authored-by: C.Y.Kun <30518686+emojiiii@users.noreply.github.com>
This commit is contained in:
程成 2022-01-18 22:26:28 +08:00 committed by GitHub
parent bf6b31e6e4
commit 9460e42ac6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 3 deletions

View File

@ -51,6 +51,24 @@ describe('Image.vue', () => {
expect(wrapper.find('.el-image__error').exists()).toBe(true)
})
test('image load sequence success test', async () => {
const wrapper = mount(Image, {
props: {
src: IMAGE_FAIL,
},
})
wrapper.setProps({
src: IMAGE_SUCCESS,
})
expect(wrapper.find('.el-image__placeholder').exists()).toBe(true)
await doubleWait()
expect(wrapper.emitted('error')).toBeUndefined()
expect(wrapper.find('.el-image__inner').exists()).toBe(true)
expect(wrapper.find('img').exists()).toBe(true)
expect(wrapper.find('.el-image__placeholder').exists()).toBe(false)
expect(wrapper.find('.el-image__error').exists()).toBe(false)
})
test('imageStyle fit test', async () => {
const fits = ['fill', 'contain', 'cover', 'none', 'scale-down']
for (const fit of fits) {

View File

@ -115,8 +115,21 @@ export default defineComponent({
hasLoadError.value = false
const img = new Image()
img.addEventListener('load', (e) => handleLoad(e, img))
img.addEventListener('error', handleError)
const currentImageSrc = props.src
// load & error callbacks are only responsible for currentImageSrc
img.addEventListener('load', (e) => {
if (currentImageSrc !== props.src) {
return
}
handleLoad(e, img)
})
img.addEventListener('error', (e) => {
if (currentImageSrc !== props.src) {
return
}
handleError(e)
})
// bind html attrs
// so it can behave consistently
@ -125,7 +138,7 @@ export default defineComponent({
if (key.toLowerCase() === 'onload') return
img.setAttribute(key, value as string)
})
img.src = props.src
img.src = currentImageSrc
}
function handleLoad(e: Event, img: HTMLImageElement) {