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

Vue子组件向父组件传值异常:传递PointerEvent而非btnValue

问题分析与解决方案

问题根源

  1. 原生事件与自定义事件混淆:你在ButtonPanel中给Button组件绑定的@click是浏览器原生点击事件,而非Button组件自身触发的自定义事件,因此addToExpression方法接收到的是浏览器的PointerEvent对象,而非按钮的btnValue。
  2. 模板中错误使用this:Vue模板上下文无需通过this访问props属性,直接使用变量名即可,虽然这不是核心问题,但需修正以符合Vue规范。

修正步骤

1. 修改Button组件,触发自定义事件

将Button组件的点击事件改为触发自定义事件(避免与原生click冲突),直接传递btnValue:

<template>
  <div class="button" @click="handleClick">
    <h2 class="text-white m-0">{{ btnValue }}</h2>
  </div>
</template>

<script>
export default {
  name: 'Button',
  props: {
    btnValue: String
  },
  methods: {
    handleClick() {
      this.$emit('btn-click', this.btnValue);
    }
  }
}
</script>

2. ButtonPanel监听自定义事件

将ButtonPanel中对Button组件的事件监听改为自定义的btn-click,确保接收正确的btnValue:

<template>
  <div class="button-panel">
    <Button @btn-click="addToExpression" btn-value="1"></Button>
    <Button @btn-click="addToExpression" btn-value="2"></Button>
    <!-- 其他按钮按此格式修改 -->
  </div>
</template>

<script>
import Button from "@/components/Button";

export default {
  name: 'ButtonPanel',
  components: { Button },
  methods: {
    addToExpression(value) {
      this.$emit('update-expression', value);
    }
  }
}
</script>

3. Calculator组件保持不变

你的Calculator组件逻辑无问题,无需修改。现在点击按钮后,expression会正确追加按钮的btnValue。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:04:54