[bugfix] Image: load event not triggered when enable lazy-load

This commit is contained in:
陈嘉涵 2019-06-08 10:05:53 +08:00
parent c1ecc21757
commit 168730d2ac
3 changed files with 97 additions and 6 deletions

View File

@ -43,12 +43,42 @@ export default sfc({
}
},
created() {
const { $Lazyload } = this;
if ($Lazyload) {
$Lazyload.$on('loaded', this.onLazyLoaded);
$Lazyload.$on('error', this.onLazyLoadError);
}
},
beforeDestroy() {
const { $Lazyload } = this;
if ($Lazyload) {
$Lazyload.$off('loaded', this.onLazyLoaded);
$Lazyload.$off('error', this.onLazyLoadError);
}
},
methods: {
onLoad(event) {
this.loading = false;
this.$emit('load', event);
},
onLazyLoaded({ el }) {
if (el === this.$refs.image && this.loading) {
this.onLoad();
}
},
onLazyLoadError({ el }) {
if (el === this.$refs.image && !this.error) {
this.onError();
}
},
onError(event) {
this.error = true;
this.loading = false;
@ -85,10 +115,6 @@ export default sfc({
},
style: {
objectFit: this.fit
},
on: {
load: this.onLoad,
error: this.onError
}
};
@ -97,10 +123,12 @@ export default sfc({
}
if (this.lazyLoad) {
return <img vLazy={this.src} {...imgData} />;
return <img ref="image" vLazy={this.src} {...imgData} />;
}
return <img src={this.src} {...imgData} />;
return (
<img src={this.src} onLoad={this.onLoad} onError={this.onError} {...imgData} />
);
}
},

View File

@ -7,6 +7,15 @@ exports[`lazy load 1`] = `
</div>
`;
exports[`lazy-load error event 1`] = `
<div class="van-image">
<div class="van-image__error"><i class="van-icon van-icon-warning-o" style="font-size: 22px;">
<!----></i></div>
</div>
`;
exports[`lazy-load load event 1`] = `<div class="van-image"><img class="van-image__img"></div>`;
exports[`load event 1`] = `<div class="van-image"><img src="https://img.yzcdn.cn/vant/cat.jpeg" class="van-image__img"></div>`;
exports[`load event 2`] = `

View File

@ -7,6 +7,7 @@ test('click event', () => {
wrapper.trigger('click');
expect(wrapper.emitted('click')[0][0]).toBeTruthy();
wrapper.destroy();
});
test('load event', () => {
@ -47,3 +48,56 @@ test('lazy load', () => {
expect(wrapper).toMatchSnapshot();
});
test('lazy-load load event', done => {
const wrapper = mount(Image, {
propsData: {
lazyLoad: true,
src: 'https://img.yzcdn.cn/vant/cat.jpeg'
},
mocks: {
$Lazyload: {
$on(eventName, hanlder) {
if (eventName === 'loaded') {
setTimeout(() => {
hanlder({ el: null });
hanlder({ el: wrapper.find('img').element });
expect(wrapper.emitted('load').length).toEqual(1);
expect(wrapper).toMatchSnapshot();
wrapper.destroy();
});
}
},
$off() {
done();
}
}
}
});
});
test('lazy-load error event', done => {
const wrapper = mount(Image, {
propsData: {
lazyLoad: true
},
mocks: {
$Lazyload: {
$on(eventName, hanlder) {
if (eventName === 'error') {
setTimeout(() => {
hanlder({ el: null });
hanlder({ el: wrapper.find('img').element });
expect(wrapper.emitted('error').length).toEqual(1);
expect(wrapper).toMatchSnapshot();
wrapper.destroy();
});
}
},
$off() {
done();
}
}
}
});
});