NuxtJS中AddEventListener绑定带参函数不执行,报handleSubmit不是函数如何解决?
问题根因
- this指向错误:click事件的回调你使用了普通匿名函数,普通函数在DOM事件回调中this会绑定到触发事件的DOM元素(报错信息中的
SVGSVGElement就是你点击的星星元素),而非Nuxt/Vue的组件实例,自然无法访问到定义在methods中的handleSubmit方法。 - 变量命名冲突:forEach遍历的元素形参命名为
el,click事件的事件对象形参也命名为el,虽然你这里使用currentTarget暂时规避了问题,但属于潜在的语法隐患。 - API使用错误:
setup是Vue3组合式API的顶层入口选项,不允许定义在methods内部,methods中只能存放业务方法函数,你当前的代码结构本身不符合Vue语法规范。
修复方案
快速修复现有写法
- 将原本写在
methods中的setup逻辑移动到mounted生命周期钩子中(只有DOM挂载完成后才能选中对应元素绑定事件) - 把事件回调的普通函数改为箭头函数,箭头函数没有独立this,会继承外层作用域的this指向组件实例
- 修正冲突的变量命名,将事件回调的形参改为
e/event避免和元素变量冲突
修复后的选项式API代码示例:
export default { methods: { async handleSubmit(recipe, userRating) { // 原有业务逻辑 } }, mounted() { // 自行补充recipe的取值逻辑 const recipe = /* 你的recipe数据 */ document.querySelectorAll('.recipe-rating > .star').forEach(el => { // 改用箭头函数,修正事件对象命名 el.addEventListener('click', e => { const userRating = e.currentTarget.getAttribute('data-rating') this.handleSubmit(recipe, userRating) }, false) }) } }
更规范的Vue写法优化
完全不需要手动操作DOM绑定事件,直接在模板中绑定@click事件即可,从根源规避this指向和DOM操作问题:
<template> <div class="recipe-rating"> <!-- 假设星星是循环渲染的,直接绑定点击事件传参 --> <svg v-for="rating in 5" :key="rating" class="star" @click="handleSubmit(recipe, rating)" > <!-- 星星图标内容 --> </svg> </div> </template> <script> export default { data() { return { recipe: /* 你的recipe数据 */ } }, methods: { async handleSubmit(recipe, userRating) { // 原有业务逻辑 } } } </script>
内容的提问来源于stack exchange,提问作者Niklas
相关产品推荐
相关产品推荐

