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

Vue子组件v-model未更新data数据问题求助

问题分析与解决方案

你的核心问题在于:增减按钮调用的是父组件传入的函数,但这些函数并未更新子组件本地的kfData.kf_units_leaking值——v-model绑定的是子组件data中的字段,若数据源未被正确修改,自然会出现输入框数值变化但data值始终不变的情况。

下面提供两种修复方案,优先推荐第一种(更符合Vue组件职责划分):

方案一:子组件内部维护增减逻辑(推荐)

让子组件自己管理状态,增减操作直接修改本地data,变化后再通知父组件,逻辑更清晰且组件耦合度低。

修改后的完整代码:

<template>
  <div>
    <input
      @click="decrement"
      type="button"
      value="-"
      class="btn button-minus border icon-shape icon-sm lh-0 bg-dark text-light"
    />
    <input
      id="kfUnitsLeaking"
      type="number"
      step="1"
      v-model="kfData.kf_units_leaking"
      name="quantity"
      class="form-control quantity-field border-0 text-center w-25"
      @change="sendChildData(kfData)"
    />
    <input
      @click="increment"
      type="button"
      value="+"
      class="btn button-plus border icon-shape icon-sm lh-0 bg-dark text-light"
    />
  </div>
</template>

<script>
export default {
  name: 'audittedKitchenFaucets',
  props: {
    sendChildData: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      kfData: {
        kf_units_leaking: 0
      }
    }
  },
  methods: {
    increment() {
      this.kfData.kf_units_leaking += 1
      this.sendChildData(this.kfData)
    },
    decrement() {
      // 防止数值小于0
      if (this.kfData.kf_units_leaking > 0) {
        this.kfData.kf_units_leaking -= 1
        this.sendChildData(this.kfData)
      }
    }
  }
}
</script>

方案二:复用父组件增减函数(耦合度较高)

若必须依赖父组件的增减逻辑,需让父函数接收子组件的data对象并直接修改,确保子组件数据源同步更新。

父组件中修改增减函数:

// 父组件methods部分
incrementValue(childData) {
  childData.kf_units_leaking += 1
},
decrementValue(childData) {
  if (childData.kf_units_leaking > 0) {
    childData.kf_units_leaking -= 1
  }
}

子组件模板修改点击事件:

<!-- 减号按钮 -->
<input
  @click="
    decrementValue(kfData)
    sendChildData(kfData)
  "
  type="button"
  value="-"
  class="btn button-minus border icon-shape icon-sm lh-0 bg-dark text-light"
/>

<!-- 加号按钮 -->
<input
  @click="
    incrementValue(kfData)
    sendChildData(kfData)
  "
  type="button"
  value="+"
  class="btn button-plus border icon-shape icon-sm lh-0 bg-dark text-light"
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:06:24