如何防止来自VueJs组件中的事件侦听器的多次调用?

我正在像这样在事件侦听器上调用特定函数。

mounted() {
    window.addEventListener("message", this.call);   },

methods: {
    call(e){
       if (e.data === "test"){
          this.call2()
       }
    }
    call2(){
       console.log("called call2")
    }
}

在第一次尝试时,call2被调用一次。但是在第二次尝试时,会call2被调用两次,并且会在控制台上显示两次“被调用的 call2”。等等。对于每次尝试,它只会增加call2单个操作中调用的次数。有什么办法可以防止这种情况吗?

回答

始终删除beforeDestroy生命周期挂钩中的事件侦听器以防止泄漏侦听器。

//Add the event listener
mounted() {
    window.addEventListener("message", this.call);   
},

//Remove the event listener
beforeDestroy() {
    window.removeEventListener("message", this.call);   
},

查看 Vue 生命周期以供参考:


以上是如何防止来自VueJs组件中的事件侦听器的多次调用?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>