博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue如何正确销毁当前组件的scroll事件?
阅读量:6895 次
发布时间:2019-06-27

本文共 2027 字,大约阅读时间需要 6 分钟。

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

 

转载于:https://www.cnblogs.com/beileixinqing/p/7771327.html

你可能感兴趣的文章
python matplotlib及sklearn安装
查看>>
困惑2017?
查看>>
KOTree
查看>>
BlockAlertsAnd-ActionSheets
查看>>
开源 java CMS - FreeCMS2.5 标签formTable自定义表单
查看>>
FreeCMS视频教程 将FreeCMS导入myeclipse
查看>>
Android 8.0 SystemUI(一):图文并茂的介绍 :D
查看>>
1wifi 简介(框架)
查看>>
internet && intranet
查看>>
go get报错 error: RPC failed; result=56, HTTP code =
查看>>
串行(Sequential)、并发(Concurrent)、并行(parallel)与分布式
查看>>
JAVA NIO学习笔记之Channel(基础篇)
查看>>
Xcode升级到6.4之后插件无法使用,重新安装最新也无法使用的解决办法
查看>>
秒懂科技新概念
查看>>
eclipse启动tomcat无法访问
查看>>
Notepad++ 书签
查看>>
TiDB 集群测试
查看>>
十天学会php之第五天
查看>>
Java基础10
查看>>
jquery基础学习二
查看>>