I recently encountered a problem concerning event listening in Vue directives. Within my component, I have the following code:
function setHeaderWrapperHeight() { ... }
function scrollEventHandler() { ... }
export default {
...
directives: {
fox: {
inserted(el, binding, vnode) {
setHeaderWrapperHeight(el);
el.classList.add('header__unfixed');
window.addEventListener(
'scroll',
scrollEventListener.bind(null, el, binding.arg)
);
window.addEventListener(
'resize',
setHeaderWrapperHeight.bind(null, el)
);
},
unbind(el, binding) {
console.log('Unbound');
window.removeEventListener('scroll', scrollEventListener);
window.removeEventListener('resize', setHeaderWrapperHeight);
}
}
}
...
}
Every time I change the router path, this component is re-rendered by assigning the current route path to the :key
prop. However, the issue lies in the fact that the event listeners are not being removed or destroyed, causing significant performance problems. How can I properly remove these event listeners?