zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue 创建监听,和销毁监听(addEventListener, removeEventListener)

Vue 创建 监听 销毁 addEventListener
2023-09-11 14:20:08 时间

最近在做一个有关监听scroll的功能, 发现我添加监听之后一直不起作用:

  1.  
    mounted() {
  2.  
    window.addEventListener("scroll", this.setHeadPosition); //this.setHeadPosition方法名
},

  后来发现要在后面添加一个true之后才行:

  1.  
    mounted() {
  2.  
    window.addEventListener("scroll", this.setHeadPosition, true);
  3.  
    },

  而在离开是的时候需要销毁监听: (在destroyed里面销毁), 否则监听会一直存在, 因为这是单页面应用, 页面并未关闭.

  1.  
    destroyed() {
  2.  
    window.removeEventListener("scroll", this.setHeadPosition, true);
  3.  
    },

  在销毁的时候一定也要加上true, 否则销毁不起作用.

 如果该组件时被keep-alive组件包裹,切换到该组件,触发activated钩子函数, 切换到其他组件触发deactivated钩子函数, 但是组件并没有销毁

  <keep-alive >
      <router-view></router-view>
    </keep-alive>

 

 activated() {
    // 全局绑定滚动事件,
    window.addEventListener("scroll", this.handleScroll);
  },
  deactivated() {
    // 组件消失,解绑scroll事件
    window.removeEventListener("scroll", this.handleScroll);
  }

 

转载于:https://www.cnblogs.com/lianxisheng/p/10802250.html