vue 实现懒加载请求数据

<template>
  <div class="test-box" ref="box">
    <div class="aaa"></div>
    <div 
      class="test"
      ref="test"
      v-for="(item, index) in list"
      :key="index"
      :style="`background-color: ${item.color};`"
    >
      {
   
   { index }} -- {
   
   { item.color }}
    </div>
  </div>
</template>

<script>
export default {
      
      
  data () {
      
      
    return {
      
      
      list: [
        {
      
       color: '#5c2223' },
        {
      
       color: '#c04851' },
        {
      
       color: '#894e54' },
        {
      
       color: '#ec9bad' },
        {
      
       color: '#951c48' },
        {
      
       color: '#62102e' },
        {
      
       color: '#2b73af' },
        {
      
       color: '#93b5cf' },
        {
      
       color: '#428675' },
      ],
      visualHeight: 0,  // 可视高度
    }
  },

  methods: {
      
      
    // 页面滚动事件
    handleScroll() {
      
      
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      for (let i = 0; i < this.list.length; i++) {
      
      
        if ((this.list[i].top <= scrollTop + this.visualHeight) && !this.list[i].after) {
      
      
          // 元素位置 <= 滚动值 + 可视高度,需要加载,并且是未加载过的
          console.log('加载', this.list[i].color);  // 此处应该是接口请求
          this.list[i].after = true;
          this.$forceUpdate();
        }
      }
    },

    // 获取元素高度
    getElementHeight() {
      
      
      let arr = this.$refs.test;
      arr.forEach((item, index) => {
      
      
        // console.log(item.getBoundingClientRect());
        this.list[index].top = item.getBoundingClientRect().top;
        this.list[index].after = false;
      })
    }
  },

  mounted() {
      
      
    this.getElementHeight();
    window.addEventListener('scroll', this.handleScroll);
    console.log('可视高度', document.documentElement.clientHeight);
    this.visualHeight = document.documentElement.clientHeight;
    // 模拟首次进入页面,无滚动的情况
    this.handleScroll();
  }
}
</script>

<style scoped>
.aaa {
      
      
  height: 1000px;
  background-color: skyblue;
  margin-bottom: 20px;
}

.test {
      
      
  width: 100%;
  height: 500px;
  margin-bottom: 20px;
  text-align: center;
  font-size: 50px;
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_49524462/article/details/118678300