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

Vue3接收事件报错:渲染时访问属性未在实例上定义及表单重置失效问题

Vue表单重置问题修复方案

各异常根因与修复逻辑

  • 异常1:点击「Calculate Difference」页面自动重载
    form标签内未显式指定type的按钮默认是submit类型,点击会触发原生表单提交行为导致页面刷新。只需给计算按钮添加type="button"属性,或在点击事件后加.prevent修饰符阻止默认行为即可。
  • 异常2:点击「Reset」按钮无法重置子组件数值
    事件传递逻辑反向,你在父组件中调用$emit('reset')是向外抛事件,无法触发子组件内部的reset方法。同时子组件reset方法中直接访问calculator变量,没有加this指向实例属性,修改也不会生效。
    修复方案:给子组件绑定ref标识,父组件点击重置按钮时直接调用子组件的reset方法,同时修正子组件reset方法的变量访问逻辑。
  • 异常3:页面加载出现reset属性未定义警告
    父组件模板中给子组件绑定了v-on:reset="reset",但父实例上根本没有定义reset方法,Vue渲染时找不到对应属性就抛出该警告,直接删掉这段无效的事件绑定即可。

完整修复后代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Difference</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
  <div id="app">
    <br> Change Values, Click "Calculate Difference", then "Reset" to set Back to 0
    <br>
    <!-- 新增ref,删除无效的@reset绑定 -->
    <calculator ref="calculator" :start_val="0" :end_val="0"> </calculator>
    <br>
    <button class="button" v-on:click="onResetButton()"> Reset </button>
  </div>
</body>
<script>
  const vm = Vue.createApp({
    methods: {
      onResetButton() {
        console.log("onResetButton 调用子组件reset方法")
        // 直接通过ref调用子组件的reset方法
        this.$refs.calculator.reset();
      },
    },
  })
  vm.component('calculator', {
    props: ['start_val', 'end_val'],
    data() {
      return {
        calculator: {
          start_val: this.start_val,
          end_val: this.end_val,
          difference: this.end_val - this.start_val,
        },
      }
    },
    methods: {
      onDifference() {
        console.log("onDifference")
        this.calculator.difference = this.calculator.end_val - this.calculator.start_val
        console.log(this.calculator.difference)
      },
      reset() {
        // 加this访问实例上的calculator属性
        this.calculator.start_val = this.start_val
        this.calculator.end_val = this.end_val
        this.calculator.difference = this.end_val - this.start_val
        console.log("reset calculator")
      }
    },
    template: `
            <hr>
            <form>
                <br> Start Value : <input class="input" type="number"  v-model.number="calculator.start_val">
                <br> End Value   : <input class="input" type="number"  v-model.number="calculator.end_val">
                <br> <button type="button" class="button" v-on:click="onDifference()">Calculate Difference  </button>
            </form>
            <p>Difference : {{ calculator.difference }} </p>
            <hr>
  `
  })
  vm.mount('#app');
</script>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:54:04