Home > other >  Event listeners on elements in a Vue Modal: are they destroyed when the Modal is closed?
Event listeners on elements in a Vue Modal: are they destroyed when the Modal is closed?

Time:02-03

I'm adding an event listener for a DOM element in a component that exists within a Vue modal:

this.$bvModal.show('modal-upload-file')
this.$nextTick(() => {
        document.querySelector('#file').addEventListener('focus', () => {
          document.getElementsByClassName('file-uploads')[0].classList.add('btn-outline-primary')
          document.getElementsByClassName('file-uploads')[0].classList.remove('btn-primary')
        })
      })

The listener works great but I'd like to remove it when the Modal component closes; my application is an SPA and won't need it on other pages. Though I know that I can just use removeEventListener, my question is whether the event listeners are destroyed automatically when the Modal is closed since the elements inside the Modal no longer exist.

CodePudding user response:

If the node is destroyed (or removed from the DOM and never used again) then it'll be garbage collected along with any event listeners attached to it.

When using Vue, accessing the DOM manually and attaching event listeners like that is a red flag. Is there any reason why you can't do it the "Vue way"?

  •  Tags:  
  • Related