使用vue3对数据进行分页展示
作者:互联网
要获取用户的滚动位置,可以在末尾添加一列空白节点。每当出现空白时意味着滑倒网页最底部,则进行渲染数据。可以使用getBoundingClientRect来判断是否在页面底部。
getBoundingClientRect
用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。
vue3示例代码如下:
<script setup lang="ts"> import { onMounted, ref, computed } from 'vue' const getList = () => { // code as before } const container = ref<HTMLElement>() // container element const blank = ref<HTMLElement>() // blank element const list = ref<any>([]) const page = ref(1) const limit = 5 const maxPage = computed(() => Math.ceil(list.value.length / limit)) // List of real presentations const showList = computed(() => list.value.slice(0, page.value * limit)) const handleScroll = () => { if (page.value > maxPage.value) return const clientHeight = container.value?.clientHeight console.log(clientHeight) const blankTop = blank.value?.getBoundingClientRect().top if (clientHeight === blankTop) { // When the blank node appears in the viewport, the current page number is incremented by 1 page.value++ console.log(list.value.slice(0, page.value * limit)) } } onMounted(async () => { const res = await getList() list.value = [ {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'77dddd7'}, {text:'77dddddddddddddd7'}, {text:'7dddddddddddddddddddddddddddd77'}, {text:'eeeeeeeee777'}, {text:'777'}, {text:'7www77'}, {text:'7wee77'}, {text:'77rrr7'}, {text:'7tt77'}, {text:'7yy77'}, {text:'7uu77'}, {text:'7ii77'}, {text:'75577'}, {text:'777'}, {text:'7rrrr77'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, {text:'777'}, ] }) </script> <template> <div id="container" @scroll="handleScroll" ref="container"> <div class="sunshine" v-for="(item) in showList" :key="item.tid"> <img :src="item.src" /> <span>{{ item.text }}</span> </div> <div ref="blank"></div> </div> </template> <style> #container { height: 100px; overflow-y: scroll; } </style>
标签:777,const,分页,展示,text,list,value,vue3,page 来源: https://www.cnblogs.com/chailuG/p/16626860.html