vue判断组件是否显示_Vue-懒加载(判断元素是否在可视区域内)

上公式:

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

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

上代码:

一个多图表 懒加载 例子

:chart-data="chartData"

:chart-id="chartId">

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()

}

}

}

}

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

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


版权声明:本文为weixin_34778803原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。