长列表懒加载

2021-04-29  本文已影响0人  guoss
<template>
  <div>
    <button-new>
      <template v-slot:default="slotProps">
        <div>我是第一种作用域插槽-------{{slotProps}}</div> 
      </template>
      
      <template #header="headerProps">我是命名插槽 {{headerProps}}</template>
    </button-new>

    <div class="node" ref="node">
      大家好呀
      <div>wewe</div>
      传&输  

      <div>大家伙
        <div>12</div>
      </div>
    </div>
    <div class="lazy-load" v-scroll="scrollFun" ref="list">
      <div class="scroll-container" ref="container">
        <div class="infinite-list-phantom" :style="{height:listHeight+'px'}"></div>
        <div class="container-list" :style="{ transform: getTransform }">
          <div v-for="(item,index) in visibleData" :key="index" class="item">
            <h2>{{item}}</h2>
          </div>
        </div>
      </div>     
    </div>
    
  </div>
</template>

<script>
import buttonNew from '../components/button.vue'
export default {
  data(){
    return {
      name:'我是数据',
      name2:'我是数据2',
      listData:[],
      start:0,
      end:0,
      totalpage:0,
      oldTop:0,
      curTotal: 20,
      startOffset:0,
      itemSize:30
    }
  },
  created(){
    this.listData = Array(1000).fill(0).map((item,index)=>index+1)
  },
  mounted(){
   this.scrollFun()
  },
  computed:{
    listHeight(){
      // 当前总的列表高度
      return this.listData.length*this.itemSize
    },
    //相对向上偏移的数量
    getTransform(){
      return `translate3d(0,${this.startOffset}px,0)`
    },
    //获取真实显示列表数据
    visibleData(){
      return this.listData.slice(this.start, Math.min(this.end,this.listData.length));
    }
  },
  methods:{
    scrollFun(el){
        //当前滚动位置
      let scrollTop = this.$refs.list.scrollTop;
      //此时的开始索引
      this.start = Math.floor(scrollTop / this.itemSize);
      //此时的结束索引
      this.end = this.start + 20;
      console.log(scrollTop % this.itemSize)
      //此时的偏移量

      this.startOffset = scrollTop - 10;
     
    }
  },
  components:{
    buttonNew
  },
  directives:{
    scroll:{
      bind(el,binding){
        console.log(binding)
        el.addEventListener('scroll',()=>{
          binding.value(el)
        })
      }
    }
  }
}
</script>

<style lang="less">
// https://cloud.tencent.com/developer/article/1533206
.lazy-load {
  position: relative;
  width: 400px;
  height:600px;
  overflow: auto;
  margin: auto;
  border:1px solid rgb(136, 44, 44);
  .item {
    height:30px;
  }
  .container-list {
    position:absolute;
    top:0;
  }
}
</style>
上一篇 下一篇

猜你喜欢

热点阅读