前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue如何正确销毁当前组件的scroll事件?

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

作者头像
蓓蕾心晴
发布2018-04-12 13:51:13
2K0
发布2018-04-12 13:51:13
举报
文章被收录于专栏:前端小叙前端小叙

将方法写出来,销毁在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,而不是执行它。

感谢各位朋友的指导~

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-11-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档