站内搜索:
首页 >> 前端 >> 内容
vue如何解决addEventListener重复绑定的问题?

时间:2018/3/24 11:03:26

我在组件里用addEventListener绑定了一个滚动事件,

mounted(){
    window.addEventListener('scroll', this.scrollListener,false)
},

当再次渲染这个组件时,这个事件又被绑定了一次,我试着用removeEventListener解绑,没有成功

mounted(){
    window.removeEventListener('scroll',this.scrollListener,false)
    window.addEventListener('scroll', this.scrollListener,false)
},

因为当组件重新渲染时this.scrollListener已经不是上一个组件里的this.scrollListener了,最后的解决方案是在组件销毁的时候去解绑

mounted(){
   window.addEventListener('scroll', this.scrollListener,false)
},
destroyed(){
    window.removeEventListener('scroll',this.scrollListener,false)
}

  • 上一篇:ionic3环境搭建教程
  • 下一篇:Vue.js和MVVM基础讲解
  • 返回顶部