简体   繁体   English

返回 Nuxt 中调用事件监听器的元素

[英]Return the element that called the event listener in Nuxt

I am working on a Nuxt project where I have a my component setup with the following code.我正在开发一个 Nuxt 项目,我在其中使用以下代码设置了我的组件。 On the select-parent-container there is a click event.select-parent-container上有一个点击事件。 When a click event occurs I want to return the particular parent container that called the event.当点击事件发生时,我想返回调用该事件的特定父容器。 Do note that this runs in a loop.请注意,这是循环运行的。

<div class="flex space-x-4 select-parent-container" @click="switchItOn" v-for="option in options" :key="option.id">
 <div class="flex space-x-2 items-center select-switcher-container">
  <div class="relative w-8 h-3 bg-gray-500 rounded-full select-toggler">
   <div class="absolute h-4 w-4 rounded-full bg-white left-0 select-switch"></div>
  </div>
 </div>
 <div class="option__desc">
  <span class="option__title">{{ props.option.name }}</span>
 </div>
</div>

In my script area, I have defined a function as在我的脚本区域中,我将 function 定义为

switchItOn: function(event) {
 console.log(this)
},

Usually, in vanila javascript, calling this on the eventlistener returns the element that called the event.通常,在 vanila javascript 中,在事件监听器上调用this会返回调用事件的元素。 Here, in Nuxt, calling this returns the whole component object.在这里,在 Nuxt 中,调用this会返回整个组件 object。 I want to return the element that called it.我想返回调用它的元素。 I tried event.target , however the problem with that is it returns children element nested inside it and would not be optimal to run the particular operations I want to.我尝试了event.target ,但是问题在于它返回嵌套在其中的子元素,并且对于运行我想要的特定操作不是最佳的。

Please kindly guide me on this.请在这方面指导我。

I've tested this code based on your question and it works fine for me.我已经根据您的问题测试了这段代码,它对我来说很好。

You should pass the event parameter to the switchItOn and use event.target.parentNode as the selector.您应该将event参数传递给switchItOn并使用event.target.parentNode作为选择器。

switchItOn: function(event) {
 console.log(event.target.parentNode)
},

If you're interested in this property, you can read about it here如果你对这个属性感兴趣,你可以在这里阅读

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

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