primevue-mirror/components/lib/deferredcontent/DeferredContent.vue

63 lines
1.6 KiB
Vue
Raw Normal View History

2022-09-06 12:03:37 +00:00
<template>
<div ref="container" v-bind="ptm('root')">
2022-09-06 12:03:37 +00:00
<slot v-if="loaded"></slot>
</div>
</template>
<script>
import ComponentBase from 'primevue/base';
2022-09-06 12:03:37 +00:00
export default {
name: 'DeferredContent',
extends: ComponentBase,
2022-09-06 12:03:37 +00:00
emits: ['load'],
data() {
return {
loaded: false
2022-09-14 11:26:01 +00:00
};
2022-09-06 12:03:37 +00:00
},
mounted() {
if (!this.loaded) {
2022-09-14 11:26:01 +00:00
if (this.shouldLoad()) this.load();
else this.bindScrollListener();
2022-09-06 12:03:37 +00:00
}
},
beforeUnmount() {
this.unbindScrollListener();
},
methods: {
bindScrollListener() {
this.documentScrollListener = () => {
if (this.shouldLoad()) {
this.load();
this.unbindScrollListener();
}
};
window.addEventListener('scroll', this.documentScrollListener);
},
unbindScrollListener() {
if (this.documentScrollListener) {
window.removeEventListener('scroll', this.documentScrollListener);
this.documentScrollListener = null;
}
},
shouldLoad() {
if (this.loaded) {
return false;
2022-09-14 11:26:01 +00:00
} else {
2022-09-06 12:03:37 +00:00
const rect = this.$refs.container.getBoundingClientRect();
const docElement = document.documentElement;
const winHeight = docElement.clientHeight;
2022-09-14 11:26:01 +00:00
return winHeight >= rect.top;
2022-09-06 12:03:37 +00:00
}
},
load(event) {
this.loaded = true;
this.$emit('load', event);
}
}
2022-09-14 11:26:01 +00:00
};
2022-09-06 12:03:37 +00:00
</script>