简体   繁体   English

带参数的函数不在 Javascript AddEventListener 中运行

[英]Function with parameters does not run inside Javascript AddEventListener

In NuxtJS I am trying to run a function with two parameters when an element is clicked with an AddEventListener .在 NuxtJS 中,当使用AddEventListener单击元素时,我试图运行一个带有两个参数的函数。

async handleSubmit(recipe, userRating) {some code...}

setup(recipe) {
  document.querySelectorAll('.recipe-rating > .star').forEach(function(el) {
    el.addEventListener('click', function(el) {
        const userRating = el.currentTarget.getAttribute('data-rating');
        this.handleSubmit(recipe, userRating);
    }, false);
  });
...more code...
}

All of the code is within methods: {} , and I get the following error when clicking.所有代码都在methods: {} ,单击时出现以下错误。

Uncaught TypeError: this.handleSubmit is not a function at SVGSVGElement.eval

How can I fix the problem, and what is the problem with my code?我该如何解决这个问题,我的代码有什么问题?

On way around this problem is to use Vue.js with the HTML element instead of trough a .js file.解决这个问题的方法是使用带有HTML元素的Vue.js ,而不是通过.js文件。 With v-on:click ( se Vue docs ) we can run a function when the user clicks the HTML element.使用v-on:click ( se Vue docs ) 我们可以在用户单击HTML元素时运行一个函数。

<svg v-for="(el, i) in 5" :key="i" :data-rating="el" @click="handleSubmit(recipe, el)">
  <polygon />
</svg>

Note: v-on:click changes to @click with ESLint .注意: v-on:click使用ESLint @click

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

相关问题 javascript addEventListener函数参数 - javascript addEventListener function parameters javascript - 将事件和参数传递给使用 addEventListener 调用的 function - javascript - Pass Event and Parameters to function called with addEventListener JavaScript addEventListener使函数直接运行 - JavaScript addEventListener makes function run directly 在addEventListener外部声明的JavaScript函数不起作用 - JavaScript function declared outside addEventListener does not work Javascript:transitionend 的 addEventListener 不执行 function - Javascript: addEventListener for transitionend does not execute function addEventListener具有命名函数和参数 - addEventListener with named function and parameters 我无法使用addEventListener Javascript / Jquery将参数传递给函数 - I can not pass parameters to a function using addEventListener Javascript/Jquery 在javascript中使用addEventListener设置单独的函数参数以具有唯一ID - Setting separate function parameters in javascript with addEventListener to have unique ids window.addEventListener(“load”,函数()内部的Javascript函数未定义 - 为什么? - A Javascript function inside of the window.addEventListener(“load”,function() is not defined - why? 使用addEventListener运行时“不是函数” - “Not a function” when run with addEventListener
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM