<!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>
性能优化:虚拟列表的简单实现
于 2024-05-20 20:23:46 首次发布