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

vue 监听页面滚动

vue 监听页面滚动

  • 一、全局监听页面滚动
  • 二、组件内监听页面滚动
  • 注意事项:


一、全局监听页面滚动

在main.js或你的入口文件中添加一个全局的滚动事件监听器。

// 在 main.js 或入口文件中
app.config.globalProperties.$onScroll = function (callback) {window.addEventListener('scroll', callback);
};app.config.globalProperties.$offScroll = function (callback) {window.removeEventListener('scroll', callback);
};

在组件中使用:

export default {mounted() {this.$onScroll(this.handleScroll);},beforeUnmount() {this.$offScroll(this.handleScroll);},methods: {handleScroll() {console.log('页面正在滚动');// 在这里编写你的滚动逻辑}}
}

二、组件内监听页面滚动

在单个组件内监听滚动事件,可以在该组件的mounted钩子中添加事件监听器,在beforeUnmount钩子中移除它,以避免内存泄漏。

export default {mounted() {window.addEventListener('scroll', this.handleScroll);},beforeUnmount() {window.removeEventListener('scroll', this.handleScroll);},methods: {handleScroll() {console.log('页面正在滚动');// 在这里编写你的滚动逻辑}}
}

注意事项:

防抖和节流:频繁的滚动事件可能会对性能产生影响,尤其是在移动设备上。使用lodash的_.throttle或_.debounce可以帮助减少这种情况的发生。例如,使用节流:

import _ from 'lodash';export default {mounted() {this.handleScroll = _.throttle(this.handleScroll, 200); // 每200毫秒最多触发一次handleScroll函数window.addEventListener('scroll', this.handleScroll);},beforeUnmount() {window.removeEventListener('scroll', this.handleScroll);},methods: {handleScroll() {console.log('页面正在滚动');// 在这里编写你的滚动逻辑}}
}

使用Vue 3 Composition API:如果使用的是Vue 3,可以更灵活地使用Composition API,例如onMounted和onUnmounted钩子:

import { onMounted, onUnmounted } from 'vue';
import _ from 'lodash'; // 如果你需要防抖或节流功能的话export default {setup() {const handleScroll = _.throttle(function() {console.log('页面正在滚动');// 在这里编写你的滚动逻辑}, 200); // 每200毫秒最多触发一次handleScroll函数(节流)onMounted(() => {window.addEventListener('scroll', handleScroll);});onUnmounted(() => {window.removeEventListener('scroll', handleScroll);});}
}
http://www.xdnf.cn/news/13457.html

相关文章:

  • carla与ros坐标变换
  • iOS 抖音首页头部滑动标签的实现
  • 【DAY45】 Tensorboard使用介绍
  • 《高等数学》(同济大学·第7版)第三章第五节“函数的极值与最大值最小值“
  • github.com 链接127.0.0.1
  • 征程 6E/M|如何解决量化部署时 mul 与 bool 类型数据交互的问题
  • 《为什么 String 是 final 的?Java 字符串池机制全面解析》
  • MySql简述
  • 基于GeoTools求解GeoTIFF的最大最小值方法
  • 搞了两天的win7批处理脚本问题
  • SaaS(软件即服务)和 PaaS(平台即服务)的定义及区别(服务对象不同、管理责任边界、典型应用场景)
  • GO自带日志库log包解释
  • 【二】12.关于中断
  • APM32芯得 EP.10 | 基于APM32F411控制的一个软开关电路设计分享
  • yolo格式分割标签可视化,coco-seg数据集
  • 6个月Python学习计划 Day 19 - 模块与包的实战拆分
  • 【Java】在 Spring Boot 中集成 Spring Security + JWT 实现基于 Token 的身份认证
  • 使用Spring Boot Actuator构建用户应用
  • 发布一个angular的npm包(包含多个模块)
  • Nuclei PoC 编写详解:从入门到实践
  • PostgreSQL 数据库技术峰会重庆站回顾|IvorySQL 开源实践与社区生态
  • python打卡day50
  • Leetcode 3572. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
  • 对3D对象进行形变分析
  • 基于“SpringBoot+uniapp的考研书库微信小程序设计与实现7000字论文
  • 新型DuplexSpy RAT可使攻击者完全控制Windows系统
  • 微信小程序中的计算属性库-miniprogram-computed
  • 23-Oracle 23 ai 区块链表(Blockchain Table)
  • Cursor 工具项目构建指南:MySql 数据库结构设计的 Cursor 规范
  • MongoDB 基础