简体   繁体   English

在 VueJS3/Nuxt 应用程序中添加动态事件列表

[英]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.我目前正在努力解决我想向组件添加数据属性的问题,然后根据加载 NUXT 的时间将点击事件绑定到具有此数据属性的所有节点。 Im not using v-on because i want to have this separated from current Vue logic.我没有使用 v-on,因为我想将它与当前的 Vue 逻辑分开。 So example:所以例子:

component a.vue is tagged with data-element组件 a.vue 被标记为数据元素

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

component b.vue also has HTM elements tagged with data-element组件 b.vue 也有标记为 data-element 的 HTM 元素

 <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.我尝试了上述方法并且在某种程度上起作用但在反应性设置和 DOM 更新时失败。 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.我检查了 mixins(不推荐使用 VueJS3),使用了组合 API,使用了一个突变观察器来检查 DOM 状态的变化,并根据新元素加载它的广告点击事件,查看钩子等,但现在我对什么是最好的感到困惑方式进行。 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为确保 DOM 已初始化,您需要将事件侦听器设置为“已安装”生命周期

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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