<template>
<div class="home">
<div class="wrap" ref="wrap" @scroll="lopk">
<!-- 为了显示滚动条 -->
<div ref="scrollHeight"></div>
<div class="lop" ref="lpo" :style="{transform: `translateY(${jio}px)`}">
<div v-for="(item,index) in visibleData" :key="index" class="a6">{{item}}</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return{
kko:Array(100).fill("kkkkkkk"),
size:20,//每一项元素的高度
state:0,//这个是获取从多少项开始
//这里的话 首先kop是是希望展示几条数据也就是刚开始默认值,也可以作为我们传入的值
//但nko为什么等于这个值呢? 因为再下面计算中,我们需要动态的获取star和nko,因为这俩值是作为动态的传入来写的使用的slice来选取显示的元素
kop:8,//希望展示几条数据
nko:this.kop,//希望展示几条数据
jio:0//列表内容的偏移量
}
},
mounted(){
//this.$refs.lpo.style.height=
this.$refs.wrap.style.height=this.size*this.kop + 'px'
//这里是为了扩充内容区域,怕不显示 ,算是一种优化
this.$refs.scrollHeight.style.height=this.shim.length*this.size+'px'
},
computed:{
//这个代表切割选取列表内容的部分
visibleData(){
return this.kko.slice(this.start, this.nko)
}
},
methods:{
lopk(){
//第一步获取向上滚动的长度路径
const scrollTop=this.$refs.wrap.scrollTop
//获取多少项
//这一步是计算选取的state和nko的值的
this.state = Math.ceil(scrollTop/this.size)
console.log(this.state)
//获取从state往下的可渲染的的多少个元素
this.nko=this.state +this.kop
console.log(this.nko)
//控制内容列表可渲染的区域的变化
this.jio=this.state*this.size
/*
1.先获取scrollTop的值,也就是往上滚动的内容区域的值
2.根据往上滚动的内容区域的值还有内容元素的值来获取动态的statr
3.根据我们传入希望显示的数据条数,来动态的设置从stare开始往下游走渲染多少条数据,但nko的最初开始的默认值是等于我们希望显示的条数的,因为slice这个方法数来选择要显示的dom元素的
4.然后让我们要渲染的区域动态的跟着this.state的变化来改变区域的位置
注意:暂时这个只是一个简单的思路因为存在性能优化问题,所以可以了解下核心思路
*/
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wrap{
width: 500px;
overflow: scroll;
position: relative;
}
.lop{
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.a6{
color: royalblue;
}
</style>