Vue.js父子组件通信通过$emit派发事件实现双向数据流,子组件触发'inc'/'dec'操作类型,父组件统一校验并更新quantity,总价用computed自动响应变化。

在 Vue.js 中,父子组件通信常用 $emit 触发自定义事件,配合 v-model 或 :value + @input(Vue 2)或 v-model:xxx(Vue 3)实现双向数据流。购物车中商品数量增减与总价实时更新,正是典型的父子协同场景:子组件(如 CartItem)负责操作按钮,父组件(如 CartList)维护商品列表和总价逻辑。
子组件:用 $emit 向上派发数量变更
子组件不直接修改传入的 quantity,而是通过事件通知父组件“我想加1”或“我想减1”。推荐传递操作类型('inc' / 'dec')而非新值,由父组件统一校验边界(如最小为1)。
示例(Vue 3 Composition API):
<template>
<div class="cart-item">
<span>{{ item.name }}</span>
<button @click="$emit('update:quantity', 'dec')">−</button>
<span>{{ quantity }}</span>
<button @click="$emit('update:quantity', 'inc')">+</button>
<span>¥{{ (item.price * quantity).toFixed(2) }}</span>
</div>
</template>
<p><script setup>
const props = defineProps({
item: { type: Object, required: true },
quantity: { type: Number, default: 1 }
})
const emit = defineEmits(['update:quantity'])
</script>父组件:监听事件并更新状态,驱动总价重算
父组件用 v-model:quantity(Vue 3)或 :quantity.sync(Vue 2)语法糖简化绑定,内部实际等价于 :quantity="item.quantity" + @update:quantity 监听器。
立即学习“前端免费学习笔记(深入)”;
关键点:
- 所有商品数据应存于响应式数组(如
ref([])),每项含id、name、price、quantity - 监听
update:quantity时,根据id找到对应商品,安全更新quantity(防止减至0以下) - 总价用
computed计算,自动响应任何quantity变化
总价计算:用 computed 保证响应式与性能
不要在每次 $emit 后手动调用函数求和,而是声明一个计算属性,它会自动追踪所有商品的 quantity 和 price 变化。
示例:
const cartItems = ref([
{ id: 1, name: 'iPhone', price: 5999, quantity: 2 },
{ id: 2, name: 'AirPods', price: 1299, quantity: 1 }
])
<p>const totalPrice = computed(() => {
return cartItems.value.reduce((sum, item) => {
return sum + item.price * item.quantity
}, 0)
})这样,只要任一商品的 quantity 被修改,totalPrice 就立即更新,模板中直接 {{ totalPrice.toFixed(2) }} 即可。
进阶建议:防抖提交、空状态处理、本地持久化
真实项目中可进一步优化:
- 数量变更后,用
debounce延迟同步到后端或 localStorage,避免高频请求 - 父组件判断
cartItems.length === 0渲染空购物车提示 - 初始化时从 localStorage 恢复购物车,更新后及时写入,保证页面刷新不丢失
核心逻辑清晰:子组件只发信号,父组件管状态与计算,$emit 是桥梁,computed 是自动更新引擎。不复杂但容易忽略。










