当前位置: 首页 > news >正文

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

监听页面滑动到底部

  • IntersectionObserver
  • scroll 事件监听器

IntersectionObserver

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

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

<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)。
mounted() {window.addEventListener('scroll', this.handleScroll)
}
  1. 在事件处理函数 handleScroll 中,判断页面滚动到底部的条件,如果条件成立,执行自定义事件 scroll-to-bottom
methods: {handleScroll() {const scrollTop = document.documentElement.scrollTop || document.body.scrollTopconst scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeightconst clientHeight = document.documentElement.clientHeight || window.innerHeightif (scrollTop + clientHeight >= scrollHeight) {this.$emit('scroll-to-bottom')}}
}
  1. 在需要监听滚动到底部的组件中,使用 $on 方法监听自定义事件 scroll-to-bottom,并执行相应的操作。
<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>
http://www.lryc.cn/news/118960.html

相关文章:

  • (一)创建型设计模式:2、单例模式(C++实现实例 线程安全)
  • 《练习100》86~90
  • C++——命名空间、输入、输出
  • 解锁滴滴ES的性能潜力:JDK 17和ZGC的升级之路
  • Permutation and Primes 2023牛客暑期多校训练营8 J
  • centos如何配置IP地址?
  • git clone 报错Filename too long
  • 【雕爷学编程】Arduino动手做(184)---快餐盒盖,极低成本搭建机器人实验平台3
  • redis String类型命令
  • Blazor 简单组件(0):简单介绍
  • 在vue3+vite项目中使用jsx语法
  • HCIA 路由器工作原理 及其 静态路由配置
  • 【Git】—— git的配置
  • [git] git基础知识
  • 【从零学习python 】15.深入了解字符串及字符集编码
  • 【LeetCode】打家劫舍||
  • 【Nginx】Nginx的重定向——location
  • 每日一题——滑动窗口的最大值
  • 【使用go开发区块链】之获取链上数据(03)
  • js 动态设置transformOrigin
  • docker使用tab无法自动补全命令
  • 既然jmeter也能做接口自动化,为什么还需要pytest自己搭框架?
  • Objective-C获取变量类型的方法
  • 相机可见区域,使用鼠标拖拽模型
  • Vue 2 与 Vue 3 的全面比较
  • Unity学习笔记--如何优雅简便地利用对象池生成游戏对象(进阶版)LRU + 对象池
  • 【Spring专题】Bean的声明周期流程图
  • C++实现俄罗斯方块(源码+详解)
  • 01:STM32点灯大师和蜂鸣器
  • linux pwn 基础知识