vue如何正确销毁当前组件的scroll事件?

将方法写出来,销毁在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事件,原因如下:

  1. 要销毁handleFun的话,得把handleFun写在method
  2. 应该是window.addEventListener("scroll",this.handleFun)window.removeEventListener("scroll",this.handleFun),  
  3. 而不是window.addEventListener("scroll",this.handleFun())window.removeEventListener("scroll",this.handleFun())

第二个参数应该是一个function,而不是执行它。

 

感谢各位朋友的指导~

posted @   蓓蕾心晴  阅读(5398)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示