vue中的addEventListener和removeEventListener

1、添加监听事件(addEventListener)
语法:element.addEventListener(event, function, useCapture)

event:指定事件名(注意: 不要使用 "on" 前缀。 例如,使用 "click" ,而不是使用 "onclick")

function:指定要事件触发时执行的函数(事件对象会作为第一个参数传入函数)

useCapture:指定事件是否在捕获或冒泡阶段执行,默认false(true - 事件句柄在捕获阶段执行,false-事件句柄在冒泡阶段执行)

mounted() {
window.addEventListener("resize", this.setNavLeft);
},
methods: {
listenerFunction(e) {
document.addEventListener("scroll", this.handleScroll, true);
},
}
2、移出监听事件(removeEventListener)
语法:element.removeEventListener(event, function, useCapture)

注意:在vue中销毁事件监听,一定要在destroyed生命周期中执行,在 beforeDestroy到destroyed之间,执行组件事件拆卸,在beforeDestroy中执行事件销毁是成功不了的

destroyed() {
document.removeEventListener("scroll", this.handleScroll, true);
window.removeEventListener("resize", this.setNavLeft);
},

原文地址:https://www.cnblogs.com/7c89/p/14821164.html