面试题
后端返回5万条数据,没有分页效果前端如何处理
性能优化:虚拟列表
参考以下代码实现了虚拟dom来进行数据加载
当数据在可视化区域当中显示 不在隐藏 以此类推。。。
!<template>
<div id="app">
121212
<button @click="add">添加数据</button>
<div class="container" ref="container">
<div class="scroll-wrapper" :style="style">
<div v-for="(item, index) in scrollList" :key="index" class="item">
<span>{{ item.name }}</span>
<span>{{ item.price }}</span>
<span>{{ item.category }}</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [{ name: "名称", price: "单价", category: "类型" }],
startIndex: 0,
endIndex: 60,
paddingTop: 0,
paddingBottom: 0,
allHeight: 0,
};
},
computed: {
scrollList() {
return this.list.slice(this.startIndex, this.endIndex);
},
style() {
return {
paddingTop: this.paddingTop + "px",
paddingBottom: this.paddingBottom + "px",
};
},
},
watch: {
list(val) {
const valLen = val.length;
this.allHeight = valLen * 30;
this.paddingBottom = this.allHeight - this.scrollList.length * 30;
},
},
mounted() {
const container = this.$refs.container;
container.addEventListener("scroll", () => {
const top = container.scrollTop;
this.startIndex = Math.floor(top / 30);
this.endIndex = this.startIndex + 60;
this.paddingTop = top;
if (this.endIndex >= this.list.length - 1) {
this.paddingBottom = 0;
return;
}
this.paddingBottom = this.allHeight - 600 - top;
});
},
methods: {
add() {
let arr = new Array(100000).fill(0);
arr = arr.map((item, index) => {
return {
name: "名称_" + index,
price: Math.ceil(Math.random() * 10) + "元",
category: Math.random() > 0.5 ? "蔬菜" : "水果",
};
});
this.list = [...this.list, ...arr];
},
},
};
</script>
<style>
.container {
width: 500px;
height: 600px;
overflow: auto;
border: 1px solid;
margin: 100px auto;
}
.item {
height: 29px;
line-height: 30px;
border-bottom: 1px solid #aaa;
padding-left: 20px;
display: flex;
text-align: center;
}
.item span {
flex: 1;
}
</style>