vue如何正确销毁当前组件的scroll事件?
2023-09-14 09:07:44 时间
将方法写出来,销毁在beforeDestroy写。
mounted(){ window.addEventListener("scroll",this.handleFun), }, methods:{ handleFun(){ let t = document.documentElement.scrollTop || document.body.scrollTop; let tabBar = document.getElementById("tabBar"); if( t >= 88 ) { tabBar.style.cssText="position:fixed;top:0;z-index:999"; } else { tabBar.style.position="relative"; } } }, beforeDestroy(){ window.removeEventListener("scroll",this.handleFun) }
以下几种方法同样有效:
//把scroll的匿名函数挂到this上 mounted(){ this.tabScroll(); }, methods:{ tabScroll(){ this.scroll_ = function () { let t = document.documentElement.scrollTop || document.body.scrollTop; console.log(t); let tabBar = document.getElementById("tabBar"); if( t >= 88 ) { tabBar.style.cssText="position:fixed;top:0;z-index:999"; } else { tabBar.style.position="relative"; } } window.addEventListener("scroll",this.scroll_); }, }, destroyed(){ window.removeEventListener("scroll",this.scroll_); }
methods:{ tabScroll(){ window.addEventListener("scroll",this.handleScroll); }, handleScroll(){ let t = document.documentElement.scrollTop || document.body.scrollTop; console.log(t); let tabBar = document.getElementById("tabBar"); if( t >= 88 ) { tabBar.style.cssText="position:fixed;top:0;z-index:999"; } else { tabBar.style.position="relative"; } } }, mounted(){ this.tabScroll(); }, beforeDestroy(){ window.removeEventListener("scroll",this.handleScroll); }
这里有一点需要注意:
给vue组件绑定scroll
事件,如果直接在 mounted
钩子中写window.addEventListener("scroll",handleFun()),
则页面并不会执行scroll
事件,原因如下:
- 要销毁
handleFun
的话,得把handleFun
写在method
中 - 应该是
window.addEventListener("scroll",this.handleFun)
和window.removeEventListener("scroll",this.handleFun)
, - 而不是
window.addEventListener("scroll",this.handleFun())
和window.removeEventListener("scroll",this.handleFun())
第二个参数应该是一个function,而不是执行它。
相关文章
- 使用 Vuex + Vue.js 构建单页应用
- vue项目el-input键盘事件
- [Vue] Props Validations
- [Nuxt] Add Arrays of Data to the Vuex Store and Display Them in Vue.js Templates
- vue.js3:pdf文件转图片(pdfjs-dist@2.14.305 / vue@3.2.37)
- vue.js3:element-plus使用例子:用滑块调节图片灰度(element-plus@2.2.2 / vue@3.2.36)
- EasyDSS RTMP流媒体服务器web前端:vue组件之间的传值,父组件向子组件传值
- [Nuxt] Use Vuex Actions to Delete Data from APIs in Nuxt and Vue.js
- springboot+vue实现前后端分离之后端spring部分(spring boot 2.5.4/vue.js 3.2.4)
- 如何给一个vue项目重命名(vue.js 3.2.4)
- vue elementUI表单输入时触发事件@input
- vue事件修饰符:通过@click.capture捕获内层事件(爷爷-父亲-儿子)
- Vue路由管理(菜单列表)
- 后台管理系统的权限以及vue处理权限的思路
- vue 鼠标移入移出事件执行多次(尤其ie)
- Vue学习之--------全局事件总线(2022/8/22)
- 116:vue+openlayers的loadstart事件和loadend事件( 示例代码 )
- 077:vue+openlayers加载geoserver发布的遥感影像,开启关闭AOI及影像(示例代码)
- Vue(三)双向绑定、监视函数、事件修饰符、双向绑定原理
- vue实现点击改变颜色
- vue第一天的自白