vue3(上拉/触底)加载更多

vue3(上拉/触底)加载更多

核心原理

  • 监听页面的滚动事件

    window.addEventListener('scroll', function)
    
  • 获取可视窗口高度,滚动高度,滚动条高度

    document.documentElement.clientHeight; // 获取可视高度
    document.documentElement.scrollTop     // 获取滚动高度
    document.documentElement.scrollHeight  // 获取滚动条高度
    

页面代码


<template>
  <div class="container">
    <ul>
      <li class="item" v-for="(item, index) in dataList" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
const dataList = reactive([1, 2, 3, 4])

// 节流方法
const throttle = (func, delay) => {
  let timer = null;
  return function () {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null
      }, delay)
    }
  }
}
// 触底函数
const onReachBottom = () => {
  window.addEventListener('scroll', throttle(onBottom, 200))
}
// 触底相应函数
const onBottom = () => {
  // 获取可视高度
  let clientHeight = document.documentElement.clientHeight;
  // 获取滚动高度
  let scrollTop = document.documentElement.scrollTop
  // 滚动条高度
  let scrollHeight = document.documentElement.scrollHeight
  if (clientHeight + scrollTop > scrollHeight) {
    console.log('触底了')
    dataList.push(dataList.length + 1)
  }
}
onReachBottom()
</script>

<style lang="scss" scoped>
.item {
  margin-top: 20px;
  width: 200px;
  height: 200px;
  font-size: 30px;
  text-align: center;
  line-height: 200px;
  background-color: hotpink;
}
</style>

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 中实现触底加载可以通过监听滚动事件,当滚动到页面底部时触发加载更多的操作。下面是一个简单的实现: 首先在模板中添加一个滚动容器及一个列表,代码如下: ``` <template> <div class="scroll-container" ref="scrollContainer" @scroll="handleScroll"> <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> </div> </template> ``` 然后在 `data` 中定义需要加载的数据、当前页数和每页的条数等相关数据: ``` <script> export default { data() { return { items: [], // 需要加载的数据 currentPage: 1, // 当前页数 pageSize: 10, // 每页的条数 total: 0 // 数据总数 }; }, methods: { // 加载更多数据 loadMore() { // 模拟异步加载数据 setTimeout(() => { for (let i = 0; i < this.pageSize; i++) { this.items.push({ id: this.total + i + 1, text: `item ${this.total + i + 1}` }); } this.total += this.pageSize; this.currentPage++; }, 1000); }, // 监听滚动事件 handleScroll() { const scrollContainer = this.$refs.scrollContainer; const scrollHeight = scrollContainer.scrollHeight; const scrollTop = scrollContainer.scrollTop; const clientHeight = scrollContainer.clientHeight; if (scrollHeight - scrollTop === clientHeight) { this.loadMore(); } } } }; </script> ``` 在 `handleScroll` 方法中,判断当前滚动容器的滚动高度和可视区域的高度是否相等,如果相等则触发加载更多的操作。 最后需要注意的是,为了确保第一次进入页面时也能触发加载操作,需要在 `mounted` 钩子函数中手动触发一次 `loadMore` 方法: ``` mounted() { this.loadMore(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值