性能优化:虚拟列表的简单实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>虚拟列表</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<style>
    *{
        margin:0;
        padding:0;
        list-style: none;
    }
    ::-webkit-scrollbar{
        display: none;
    }
    ul{
        margin: 10px auto;
        width: 400px;
        height:600px;
        background:pink;
        overflow: scroll;
    }
    ul li{
        margin: 0 0 5px;
        width:100%;
        height:60px;
        line-height: 60px;
        text-align: center;
        background:skyblue;
    }
</style>
<body>
    <div id="app">
        <ul>
           <li v-for="(item,index) in list"  :key="item">{{item}}</li>
        </ul>
    </div>
<script>
const { createApp, ref,onMounted } = Vue
createApp({
    setup() {
        //展示的列表条数 
        const size = 10
        const array =  Array.from({ length: 101 }, (item, i) => i+1);
        let list = ref(array.slice(0,size + 1))
        const start = ref(0)
        const end = ref(size)
        onMounted(()=>{
           let ul =  document.querySelector('ul')   
           const scrollY = ref(0)
           ul.onwheel = (e)=>{
               //滚轮下滑时
               if(e.deltaY > 0){
                  if(start.value >= array.length - size){
                    start.value = array.length - size
                  }else{
                     start.value ++
                  }
                  if(end.value >= array.length){
                    end.value = array.length
                  }else{
                    end.value ++
                  }
               //滚轮上滑时
               }else{
                  if(start.value <= 0){
                    start.value = 0
                  }else{
                     start.value --
                  }
                  if(end.value <= size){
                    end.value = size
                  }else{
                    end.value --
                  }
               }
               //更新视图中的列表
               list.value =  array.slice(start.value,end.value)
           }
      })
      return {
        list
      }
    }
  }).mount('#app')
</script>
</body>
</html>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值