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

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);});}
}

相关文章:

  • Linux下V2Ray安装配置指南
  • linux thermal framework(1)_概述
  • LIGHT (数据库操作)
  • 编程风格良好的条件比较语句
  • 实现转场动画
  • vue3+tdesign实现明暗主题切换
  • 6.10 Mysql 事务 锁 面试题
  • C++_核心编程_多态案例二-制作饮品
  • 赛尔发布SHARE 5系列航测相机,外业更高效,建模更优质
  • 制作一款打飞机游戏69:编辑器升级
  • AliExpress(速卖通)铺货工具,图片下载,SKU浏览,详情搬运,使用方法
  • 3分钟配置好nacos集群(docker compose)
  • Docker 创建及部署完整流程
  • (五)docker环境中配置hosts
  • 【论文阅读笔记】HaDes幻觉检测benchmark
  • 搭建gitlab ci/cd runner实现对c++项目的自动编译和打包
  • 丝杆升降机的物联网与大数据应用的具体例子
  • V837s-SDK Telnetd服务连接不上异常解决
  • A16 扁平化管理
  • YSYX学习记录(八)
  • 站长号/小程序搭建
  • 做微信公众号的网站/贵阳seo网站管理
  • 铝木门窗网站建设/阿拉善盟seo
  • 推广公司网站有哪些方式/河南关键词排名顾问
  • 六安网络推广/优化一下
  • 成都网站设计推荐/中央电视台新闻联播