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

Vue 3代码出现未定义错误求助:原可运行现失效

问题解决:Vue3 点击按钮弹出「未定义」错误

问题原因

你在按钮上使用了原生DOM的onClick事件绑定,但Vue组件内定义的increaseXp方法不属于全局作用域,原生事件无法访问到它;同时button是Vue循环里的局部变量,原生事件也识别不了,这就是报错的根源。Vue有自己的事件绑定语法,不能混用原生事件绑定来调用组件方法。

修正方案

把按钮的原生onClick替换为Vue的@click(v-on:click的简写)事件绑定语法即可。

修正后的完整代码

JavaScript部分

const {
  createApp
} = Vue
createApp({
  data() {
    return {
      mins: 0,
      cats: 0,
      xp: 0,

      buttons: [{
        name: "Gym",
        increaseValue: 10

      }, {
        name: "Sleep",
        increaseValue: 2
      }, {
        name: "Eat",
        increaseValue: 3
      }]
    }
  },
  methods: {
    increaseXp(increaseValue) {
      this.xp += increaseValue
    }
  }
}).mount('#app')

HTML部分

<head>
  <script src="https://unpkg.com/vue@3"></script>
  <script src="https://cdn.tailwindcss.com/"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Name</title>
</head>

<body class="bg-sky-100">
  <div id="app">
    <div class="max-w-3xl mx-auto">
      <h1 class="font-bold text-7xl border-b-4 pb-4 border-black w-fit text-center font-mono">Name of App</h1>
      <h2 class="font-bold text-2xl text-center mt-5">
        LEVEL
      </h2>
      <h3 class="text-center">
        {{xp}}
      </h3>
    </div>
    <div class="grid grid-cols-3 gap-3 px-3 mt-6">
      <button @click="increaseXp(button.increaseValue)" v-for="button in buttons" class="py-2 border border-black rounded bg-sky-300">
                {{button.name}}
            </button>
    </div>

  </div>
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:53:17