臨平網(wǎng)站建設(shè)互聯(lián)網(wǎng)營銷推廣怎么做
虛擬列表,實(shí)際上就是在首屏加載的時(shí)候,只加載可視區(qū)域內(nèi)需要的列表項(xiàng),當(dāng)滾動(dòng)發(fā)生時(shí),動(dòng)態(tài)通過計(jì)算獲得可視區(qū)域內(nèi)的列表項(xiàng),并將非可視區(qū)域內(nèi)存在的列表項(xiàng)刪除。該技術(shù)是解決渲染大量數(shù)據(jù)的一種解決方法。
實(shí)現(xiàn)虛擬列表,需要獲取以下幾個(gè)屬性
- 可視區(qū)域起始數(shù)據(jù)索引(startIndex)
- 可視區(qū)域結(jié)束數(shù)據(jù)索引(endIndex)
- 計(jì)算可視區(qū)域數(shù)據(jù),并渲染到頁面中
- 計(jì)算startIndex對應(yīng)的數(shù)據(jù)在整個(gè)列表中的偏移位置listTop并設(shè)置到列表上
高度固定
令A(yù)pp組件(父組件)產(chǎn)生一萬條虛擬數(shù)據(jù)來模擬接口,在List組件中實(shí)現(xiàn)對應(yīng)的功能
App組件:
<template><div><List :items="items" :size="60" :shownumber="10"></List></div>
</template><script>
import List from '@/List.vue'
export default {components: {List},computed: {// 模擬數(shù)據(jù)items() {return Array(10000).fill('').map((item, index) => ({id: index,content: index}))}}
};
</script><style scoped></style>
List組件:
<template><div class="container" :style="{ height: containerHeight }" @scroll="handleScroll" ref="container"><!-- 數(shù)據(jù)列表 --><div class="list" :style="{top:listTop}"><!-- 列表項(xiàng) --><div v-for="item in showData" :key="item.id" :style="{height:size+'px'}">{{ item.content }}</div><!-- 用于撐開高度的元素 --><div class="bar" :style="{height:barHeight}"></div></div></div>
</template><script>
export default {name: 'List',props:{// 要渲染的數(shù)據(jù)items:{type:Array,required:true},// 每條數(shù)據(jù)渲染節(jié)點(diǎn)的高度size:{type:Number,required:true},// 每次渲染DOM節(jié)點(diǎn)個(gè)數(shù)shownumber:{type:Number,required:true}},data(){return{start:0, //要展示數(shù)據(jù)的其實(shí)下標(biāo)end:this.shownumber //結(jié)束下標(biāo)}},computed:{// 最終展示數(shù)據(jù)showData(){return this.items.slice(this.start,this.end)},// 容器的高度containerHeight(){return this.size * this.shownumber + 'px'},// 撐開容器內(nèi)部高度的元素的高度barHeight(){return this.size * this.items.length + 'px'},// 列表項(xiàng)上滾動(dòng)改變top的值listTop(){return this.start * this.size + 'px'},},methods:{// 容器滾動(dòng)事件handleScroll(){// 獲取容器頂部滾動(dòng)的尺寸const scrollTop = this.$refs.container.scrollTopthis.start = Math.floor(scrollTop / this.size)this.end = this.start + this.shownumber}}
};
</script><style 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>
這樣可以實(shí)現(xiàn)一個(gè)簡單的固定高度的虛擬列表功能。