虚拟列表实现方法(vue2/vue3)

vue2+element UI 实现虚拟列表

原文地址:https://blog.csdn.net/weixin_46345861/article/details/126468246


 

 

vue3实现虚拟列表

原文地址:https://blog.csdn.net/Laollaoaolao/article/details/125052026

<div ref="listWrap" class="list-wrap" @scroll="scrollListener">
    <div class="list" ref="List">
        <slot  v-for="item in showList" :songInfo="item" :key="item.id"></slot>
    </div>
  </div>
  <script>
  import { defineComponent, computed, ref} from 'vue'
  export default defineComponent({
    setup(props) {
    const list = ref(props.list); //长列表数据
    const itemHeight = ref(props.itemHeight); //item高度
    const showNum = ref(props.showNum); //展示的数据
    const start = ref(props.start); //滚动过程中的开始索引
    const end = ref(props.end); //滚动过程中的结束索引
    const listWrap = ref(null); //获取列表视图模型节点
    const List = ref(null)//获取列表节点

    onMounted(() => {
        listWrap.value.style.height = itemHeight.value * showNum.value + "px";//设置列表视图模型的高度  
    });
    const showList = computed(() => {
      //获取展示的列表
      return list.value.slice(start.value, end.value);
    });
    const scrollListener = (() => {
           //获取滚动高度
            let scrollTop = listWrap.value.scrollTop;         
            //开始的数组索引
            start.value = Math.floor(scrollTop / itemHeight.value);
            //结束索引
            end.value = start.value + showNum.value
            List.value.style.transform =  `translateY(${start.value * itemHeight.value}px)`//对列表项进行偏移
    })
    return {
     showList, scrollListener ,List ,listWrap
    };
  },
};
</script>

你可能感兴趣的:(vue.js,javascript,前端)