简体   繁体   中英

Adding dynamic eventlistners in VueJS3/Nuxt app

Im currently struggling with something where i want to add a data attribute to a component and then based on when NUXT is loaded have a click event bind to all nodes that have this data attribute. Im not using v-on because i want to have this separated from current Vue logic. So example:

component a.vue is tagged with data-element

  <a href="/somelink" data-element>link</a>

component b.vue also has HTM elements tagged with data-element

 <button data-element>link</button> 

When the app loads i need to then loop through all data-element and bind an eventlistner to them.

I tried the above method and that works to some degree but fails when reactivity sets in and the DOM is updated. I checked mixins (not recommended using VueJS3), used composition API, used a mutation observer that checked the DOM status for changes and based on new elements loaded it ads click events, looked at hooks etc but now im getting confused at what is the best way to proceed. Some solutions work to some extend but feels hacky. Or is there a completely different approach i am missing.

To be Sure that the DOM has been initialized you need to set your event listeners on "mounted" lifecycle

mounted() {
  const elements = [...document.querySelectorAll('[data-element]')];
  elements.forEach(element => {
    element.addEventListener('click', () => { /* your code here. */ })
  })
}
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM