Vue中的虚拟列表是一种渲染大量数据的优化方式。通常,渲染大量数据时,会出现页面卡顿的情况。虚拟列表通过仅渲染当前可见的数据来避免这种卡顿。
虚拟列表的实现方式是将数据分成一个个可视区域,而非全部渲染。当用户滚动列表时,只有当前可见区域的数据被渲染。当用户滚动到列表的另一个区域时,虚拟列表会根据需要重新渲染可视区域的数据。
虚拟列表的原理和使用方法就是这样。使用虚拟列表可以提高Vue应用程序的性能,让用户可以流畅地浏览大量数据。
vue虚拟列表
需要的参数:
total: 1000, // 模拟数据条数
contentHeight: 400, // 可视化区域高度
showList: [], // 可视区域展示用的列表
startIndex: 0, // 开始位置下标
endIndex: null, // 结束下标
itemHeight: 50, // 默认每条的高度
scrollTop: 0, // 滚动条高度 顶部
showNum: 0, // 当前展示列表的高度
top: 0, // 可视区域距离顶部的距离
<template>
<div ref="contentBox" class="content-box"
:style="{ height: contentHeight + 'px' }"
@scroll="scrollListener">
<div
:style="{
position:'relative',
height: showBoxHeight
}"
>
<div
:style="{
position: 'absolute',
top: top+'px'
}"
>
<div class="box-item"
:style="{
height: itemHeight + 'px',
lineHeight: itemHeight + 'px'
}"
v-for="(item,index) in showList" :key="index"
>
{{ item }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Hello',
data() {
return {
total: 1000, // 模拟数据条数
contentHeight: 400, // 可视化区域高度
showList: [], // 可视区域展示用的列表
list: [],
startIndex: 0, // 开始位置下标
endIndex: null, // 结束下标
itemHeight: 50, // 默认每条的高度
scrollTop: 0, // 滚动条高度 顶部
showNum: 0, // 当前展示列表的高度
top: 0, // 可视区域距离顶部的距离
};
},
computed: {
showBoxHeight() {
return this.itemHeight * this.list.length + "px";
},
},
mounted() {
this.getList();
this.scrollListener();
},
methods: {
scrollListener() {
this.scrollTop = this.$refs.contentBox.scrollTop
this.showNum = Math.ceil(this.contentHeight / this.itemHeight)
this.startIndex = Math.floor(this.scrollTop / this.itemHeight)
this.endIndex = this.startIndex + this.showNum
this.showList = this.list.slice(this.startIndex , this.endIndex)
this.top = this.startIndex * this.itemHeight
},
getList() {
this.list = Array.from({ length: this.total }).map(
(_, index) => `我是第${index}条数据信息`,
);
},
},
};
</script>
<style scoped>
.content-box {
margin: 30px auto 0;
position: relative;
width: 400px;
border: 1px solid #e4e7e4;
overflow-y: auto;
box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
border-radius: 4px;
padding: 10px 0;
}
.box-item {
padding: 0 32px 0 20px;
color: #606266;
}
.content-box::-webkit-scrollbar {
width: 10px;
height: 1px;
}
.content-box::-webkit-scrollbar-thumb {
border-radius: 10px;
background: #e5e5e5;
}
.content-box::-webkit-scrollbar-track {
border-radius: 10px;
background: #ffffff;
}
</style>