【vue 监听页面滑动到底部】

监听页面滑动到底部

IntersectionObserver

在 Vue 中监听触底可以通过使用IntersectionObserver实现。IntersectionObserver是一个可以异步观察目标元素与其祖先或视窗交叉状态的API。当目标元素进入或退出视口时,会触发IntersectionObserver的回调函数。

以下是一个监听触底的示例:

vue 复制代码
<template>
  <div class="container" ref="container">
    <!-- 这里是数据列表 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      observer: null,
    }
  },
  mounted() {
    // 创建 IntersectionObserver 实例
    this.observer = new IntersectionObserver(this.handleObserve, {
      root: null,
      rootMargin: '0px',
      threshold: 1.0,
    });
    // 监听容器底部
    this.observer.observe(this.$refs.container.lastChild);
  },
  methods: {
    handleObserve(entries) {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          // 滚动到底部触发加载更多
          this.loadMoreData();
        }
      });
    },
    loadMoreData() {
      // 加载更多数据的逻辑
    },
  },
};
</script>

在mounted钩子函数中创建IntersectionObserver实例,并监听容器底部的元素。在handleObserve回调函数中判断当前元素是否可见,如果可见则触发加载更多数据的逻辑。

scroll 事件监听器

在 Vue 中监听页面滑动到底部的方法如下:

  1. 创建一个 scroll 事件监听器,并将事件绑定在根元素上(windowdocument.body)。
js 复制代码
mounted() {
  window.addEventListener('scroll', this.handleScroll)
}
  1. 在事件处理函数 handleScroll 中,判断页面滚动到底部的条件,如果条件成立,执行自定义事件 scroll-to-bottom
js 复制代码
methods: {
  handleScroll() {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
    const clientHeight = document.documentElement.clientHeight || window.innerHeight
    if (scrollTop + clientHeight >= scrollHeight) {
      this.$emit('scroll-to-bottom')
    }
  }
}
  1. 在需要监听滚动到底部的组件中,使用 $on 方法监听自定义事件 scroll-to-bottom,并执行相应的操作。
html 复制代码
<template>
  <div>
    <div v-for="item in list" :key="item.id">{{ item.text }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: []
    }
  },
  mounted() {
    this.loadMore()
    this.$on('scroll-to-bottom', this.loadMore)
  },
  methods: {
    loadMore() {
      // TODO: 加载更多数据
    }
  }
}
</script>
相关推荐
To_OC5 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
kyriewen9 小时前
我用 50 行代码重写了 React Router 核心,终于搞懂了前端路由原理
前端·javascript·react.js
Asize12 小时前
HTML5 Canvas 基础:从按帧动画到 ECharts 数据可视化
前端·javascript·canvas
默_笙12 小时前
🎄 后端给我一堆扁平数据,我 10 行代码把它变成了树
前端·javascript
前端Hardy12 小时前
又一个 AI 神器火了!
前端·javascript·后端
锋行天下12 小时前
我试图优化 Vite 的拆包,结果首屏慢了 10 倍
前端·vue.js·架构
PBitW12 小时前
GPT训练我的第二天,我表示不过如此!!!😕😕😕
前端·javascript·面试
kyriewen13 小时前
白宫直接给 OpenAI 下了限制令,GPT-5.6 不能随便放出来了
前端·javascript·面试
ZhengEnCi17 小时前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
晴虹18 小时前
vue3-scroll-more:横向滚动条-元素或页签过多滚动显示处理的组件
前端·vue.js