There is the following component:

<template> <div class="header"> Header content </div> </template> <script> export default { } </script> <style> .header { position: fixed; top: 0; left: 0; height: 100px; width: 100%; } </style> 

Question: how to add a class header-hidden to div.header , if the height of the scroll is> 200px? Where in vue is it better to hang window.on handlers? And should they be destroyed when an item is destroyed?

  • In the VueJs component, you can do everything that you would do in a native JS. Where it is convenient to assign a handler, do it there. When deleting a component, if the handler is not needed, then it is desirable to remove it - for performance reasons. - Dmytryk

1 answer 1

To work correctly, the handler is best placed in the block of the mounted or created . In the destroyed block it should be removed.

 <template> <div ref="header" class="header"> Header content </div> </template> <script> mounted(){ window.addEventListener('scroll', this.onScroll); }, methods: { onScroll() { if (window.pageYOffset > 200) { this.$refs.header.classList.add('header-hidden'); } }, }, destroyed() { window.removeEventListener('scroll', this.onScroll); } </script>