使用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>

以上代码是页面只有一个列表进行下拉加载,如果还有其它dom,则要进行判断,获取自身元素container.value?.getBoundingClientRect().bottom与blank.value?.getBoundingClientRect().bottom进行比较是否相等

 

判断元素是否在可视区域

function isElementInViewport (el) {
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

  

posted @ 2022-08-26 10:55  府谷市民小柴  阅读(1324)  评论(0编辑  收藏  举报