假设给你10万条数据前端怎么展示
- 思路
1.已知展示数据盒子的高度,和每条数据的高度,就能知道盒子最多能展示多少条数据
2.假设盒子高度为100px,每条数据高度为2px;那么 盒子最多展示50条数据,就可以知道开始下标为0,结束下标为50
3. 监听盒子的scroll滚动事件 得到滚出的距离 滚动的距离除以 数据的高度 就能得到滚动了几条数据
4. 新的开始下标就等于滚动的距离除以每条数据的高度
5. 结束下标就等于开始下标加上50
6. 实际渲染的数据 = 原始数据.slcie(开始下标,结束下标)
- 具体代码思路
父组件
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App" :arr="arr"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
computed:{
arr(){
return Array(1000).fill('').map((item,index)=>({
id:index,
content:'数据'+index
}))
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件
<template>
<div class="hello" @scroll="handleScroll" ref="scroll" style="position:relative">
<div style="position:absolute" :style="{top:lisTtop}">
<div v-for="item in list" :key="item.index" style="height:20px;" >
{{ item.content }}
</div>
</div>
<!-- 撑开盒子的高度等于原始数据的长度乘以每条数据的固定高度 我这里直接写死 因为为传入了1000条数据,每条数据的高度为20 -->
<div style="height:20000px"></div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String,
arr:{
type:Array,
default:()=>{
return []
}
}
},
computed:{
list(){
return this.arr.slice(this.start,this.end)
},
lisTtop(){
return this.start*20+'px'
}
},
data(){
return{
start:0,
end:10,
height:20,//每条数据的高度
}
},
methods:{
handleScroll(){
this.start = Math.floor(this.$refs.scroll.scrollTop/this.height) //得到滚出条数据的开始下标
//结束下标就等于 开始下标加上固定展示数量的和
this.end = this.start + 10
console.log(this.start,this.end,this.list)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello{
height:200px;
width:100px;
border:1px solid red;
overflow: hidden;
overflow-y: scroll;
}
</style>