Vue-懒加载(判断元素是否在可视区域内)

时间:2021-04-12 09:22:14

上公式:

元素距离顶部高度(elOffsetTop) >= dom滚动高度(docScrollTop)

并且元素距离顶部高度(elOffsetTop) < (dom滚动高度 + 视窗高度)

上代码:

一个多图表 懒加载 例子

<template>
<div :id="boxId" style="height: 450px">
<div v-loading="chartLoading">
<defect-flight-pattern-chart
:chart-data="chartData"
:chart-id="chartId">
</defect-flight-pattern-chart>
</div>
</div>
</template> <script>
import DefectFlightPatternChart from '~/components/metrics/defect-flight-pattern-chart'
export default {
components: {
DefectFlightPatternChart
},
props: {
projectUuid: { type: String, default: '' },
chartIndex: { type: Number, default: 0 }
},
data () {
return {
chartData: {},
chartLoading: false,
isLoaded: false,
boxId: 'dashboard-chart-box-',
chartId: 'dashboard-chart-'
}
},
mounted () {
this.chartId = this.chartId + this.chartIndex + Math.floor(Math.random() * 1000)
this.boxId = this.chartId + '-box'
this.$nextTick(() => {
this.scroll()
window.addEventListener('scroll', this.scroll)
})
},
destroyed () {
window.removeEventListener('scroll', this.scroll, false)
},
methods: {
async getChartData () {
try {
this.isLoaded = true
this.chartLoading = true
const { data } = await this.$axios.get(`/api/v1/projects/${this.projectUuid}/issues/trend`)
this.chartData = data
this.chartLoading = false
} catch (e) {
console.log(e)
}
},
async scroll () {
const elOffsetTop = document.getElementById(this.boxId).offsetTop
const docScrollTop = document.documentElement.scrollTop - 230
if (elOffsetTop >= docScrollTop && elOffsetTop < (docScrollTop + window.innerHeight) && !this.isLoaded) {
await this.getChartData()
}
}
}
}
</script>

觉得有帮助的小伙伴点个赞支持下~

觉得有帮助的小伙伴点个赞~