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

Vue如何将父组件props传递给子组件的input绑定值

问题排查及解决

核心错误点

  • 父组件未使用动态绑定传递props
    当前父组件写法<Counter quantity="item.quantity"/>传递的是静态字符串"item.quantity",而非item.quantity对应的变量值。Vue传递动态变量必须使用v-bind:(简写为:)修饰props字段。
  • 子组件直接修改props违反单向数据流规则
    Vue规定props为只读属性,子组件不可直接修改父组件传入的props。当前代码直接用v-model绑定quantity、在计数方法中直接修改this.quantity的操作会触发框架警告,且修改无法同步回父组件源数据。

修复方案

父组件Cart修改

将调用代码改为动态绑定,同时监听子组件抛出的更新事件修改源数据:

<!-- 写法1:完整写法 -->
<Counter :quantity="item.quantity" @update:quantity="item.quantity = $event"/>

<!-- 写法2:v-model语法糖,效果和上面一致 -->
<Counter v-model:quantity="item.quantity"/>

子组件Counter修改

新增中间计算属性对接props和更新事件,修改后完整代码如下:

<template>
    <div id="counter">
        <button class="minus" @click="countDown"><i :class="quantity == 0 ? 'disabled' : ''" class="fas fa-minus"></i></button>
        <div class="count-number"><input class="counter-content" type="number" v-model="localQuantity"></div>
        <button class="plus" @click="countUp"><i class="fas fa-plus"></i></button>
    </div>
</template>
<script>
    export default {
        props: {
            quantity: Number
        },
        computed: {
            localQuantity: {
                get() {
                    return this.quantity
                },
                set(newVal) {
                    // 将输入值转为数字类型,避免类型不匹配问题
                    this.$emit('update:quantity', Number(newVal))
                }
            }
        },
        methods: {
            countUp() {
                this.localQuantity++;
            },
            countDown() {
                if(this.quantity > 0) {
                    this.localQuantity--;
                }
            },
        }
    }
</script>

修复后子组件所有修改操作都会通过事件通知父组件更新源数据,符合Vue单向数据流设计规范,无警告且数据可正常双向同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:54:02