Reputation: 1096
I have a Vue component /foo
that listens to scroll
and resize
events:
export default {
name: 'foo',
mounted() {
window.onresize = function (event) {
//doing stuff
console.log('doing onresize stuff');
};
window.addEventListener('scroll', function (event) {
//doing stuff
console.log('doing scroll stuff');
});
...
Which works correctly. However, when I use VueRouter
and signout and away from /foo
to another component /bar
my console is still being filled with scroll
and resize
events when I scroll and resize on the new /bar
component:
doing scroll stuff
doing onresize stuff
doing scroll stuff
doing scroll stuff
doing scroll stuff
How can I completely stop all references and delete(?) the previous page (/foo
) from memory so that this does not happen?
Upvotes: 1
Views: 692
Reputation: 1668
You can use removeEventListener
const handler = (event) => console.log(event)
export default {
mounted() {
window.addEventListener('scroll', handler)
},
beforeDestroy() {
window.removeEventListener('scroll', handler)
}
}
W3schools has more examples.
If you're listening to events on DOM, you can use Vue's v-on
or @
syntax, e.g. @click
. Vue will handle the event listeners for you in this case.
Upvotes: 2