网站搭建的步骤,如何做中英文网站,盐城网站建设服务,修改wordpress注册邮件虚拟列表#xff0c;实际上就是在首屏加载的时候#xff0c;只加载可视区域内需要的列表项#xff0c;当滚动发生时#xff0c;动态通过计算获得可视区域内的列表项#xff0c;并将非可视区域内存在的列表项删除。该技术是解决渲染大量数据的一种解决方法。 实现虚拟列表实际上就是在首屏加载的时候只加载可视区域内需要的列表项当滚动发生时动态通过计算获得可视区域内的列表项并将非可视区域内存在的列表项删除。该技术是解决渲染大量数据的一种解决方法。 实现虚拟列表需要获取以下几个属性
可视区域起始数据索引startIndex可视区域结束数据索引endIndex计算可视区域数据并渲染到页面中计算startIndex对应的数据在整个列表中的偏移位置listTop并设置到列表上
高度固定
令App组件父组件产生一万条虚拟数据来模拟接口在List组件中实现对应的功能
App组件
templatedivList :itemsitems :size60 :shownumber10/List/div
/templatescript
import List from /List.vue
export default {components: {List},computed: {// 模拟数据items() {return Array(10000).fill().map((item, index) ({id: index,content: index}))}}
};
/scriptstyle scoped/styleList组件
templatediv classcontainer :style{ height: containerHeight } scrollhandleScroll refcontainer!-- 数据列表 --div classlist :style{top:listTop}!-- 列表项 --div v-foritem in showData :keyitem.id :style{height:sizepx}{{ item.content }}/div!-- 用于撑开高度的元素 --div classbar :style{height:barHeight}/div/div/div
/templatescript
export default {name: List,props:{// 要渲染的数据items:{type:Array,required:true},// 每条数据渲染节点的高度size:{type:Number,required:true},// 每次渲染DOM节点个数shownumber:{type:Number,required:true}},data(){return{start:0, //要展示数据的其实下标end:this.shownumber //结束下标}},computed:{// 最终展示数据showData(){return this.items.slice(this.start,this.end)},// 容器的高度containerHeight(){return this.size * this.shownumber px},// 撑开容器内部高度的元素的高度barHeight(){return this.size * this.items.length px},// 列表项上滚动改变top的值listTop(){return this.start * this.size px},},methods:{// 容器滚动事件handleScroll(){// 获取容器顶部滚动的尺寸const scrollTop this.$refs.container.scrollTopthis.start Math.floor(scrollTop / this.size)this.end this.start this.shownumber}}
};
/scriptstyle scoped
.container{overflow-y: scroll;background-color: rgb(150,150,150,.5);font-size: 20px;font-weight: bold;line-height: 60px;width: 500px;margin: 0 auto;position: relative;text-align: center;
}
.list{position: absolute;top: 0;width: 100%;
}
/style这样可以实现一个简单的固定高度的虚拟列表功能。