You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt 3模块组件点击触发过多递归错误如何解决?

问题描述

我正在构建一个Nuxt 3模块,其中包含一个简单的按钮组件。点击按钮时会翻转一个布尔值,该变量的逻辑存储在独立文件中,使用Pinia作为状态管理库。

Store 代码

import { defineStore } from "pinia"

export const getLogic = defineStore('logic', {
  state: () => {
    return{
      status: false,
    }
  },
  actions: {
    flip() {
      this.status = !this.status
    },
  },
  getters: {
    getStatus() { return this.status }
  }
})

按钮组件代码

<template>
  <button onClick="logic.flip()">
    <slot />
  </button>
</template>


<script lang="ts">
import { getLogic } from "../../stores/logic"

export default {
  setup() {
    const logic = getLogic()
    return { logic }
  } 
}
</script>

测试调用方式

<template>
  <Button >
    Button
  </Button>
</template>

错误信息

点击按钮后,浏览器控制台出现以下错误:

Uncaught InternalError: too much recursion
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:162
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174
    callWithAsyncErrorHandling runtime-core.esm-bundler.js:174

我逻辑里没用到递归,这问题怎么解决?


解决方案

问题出在按钮的事件绑定上——你用了原生的onClick(大写C),但在Vue模板里应该用Vue的指令@click(或v-on:click)。

原生onClick接收字符串形式的代码,会在全局作用域执行,你写的logic.flip()在这里会因作用域不匹配触发意外的递归调用。

修改按钮组件的模板部分即可:

<template>
  <button @click="logic.flip()">
    <slot />
  </button>
</template>

也可以用完整指令写法:

<template>
  <button v-on:click="logic.flip()">
    <slot />
  </button>
</template>

修改后,点击按钮就能正常触发Pinia store里的flip方法,不会再出现递归错误。

内容的提问来源于stack exchange,提问作者rajohs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:30:56