Vue 3 用 ref 或 reactive 管理购物车数据,配合 computed 实现总价自动响应更新;ref 包裹商品数组,v-model.number 绑定数量,computed 基于 price×count 实时汇总总价,支持链式计算与业务校验。

Vue 3 用 ref 或 reactive 管理购物车数据,再配合 computed 自动算总价——数量一变,总价立刻响应更新,不用手动触发、也不重复计算。
用 ref 管理商品列表和单个数量
每个商品的数量要能被 Vue 追踪变化,必须是响应式数据。推荐用 ref 包裹整个数组,或用 reactive 定义对象结构:
const cartItems = ref([{ id: 1, name: '咖啡', price: 28, count: 1 }])- 增减操作直接改
item.count,比如item.count++或item.count = Math.max(1, item.count - 1) - v-model 绑定输入框时加
.number修饰符,避免字符串拼接(如v-model.number="item.count")
用 computed 实时汇总总价
总价不是静态值,它依赖所有商品的 price × count。computed 会自动监听这些字段,只在真正变化时重算:
将静态 Vue 页面(index.vue)改造为动态页面(Custom.vue);稿源仅限 index.vue、其引用的 CSS 与资源路径,禁止参考仓库内其他文件。Invoke when user wants to transform a static Vue page into a dynamic data-driven page with Element UI components.
const totalPrice = computed(() => { return cartItems.value.reduce((sum, item) => sum + item.price * item.count, 0) })- 模板中直接写
{{ totalPrice }},无需调用函数,也不用 watch 手动监听 - 如果加了优惠券或运费逻辑,可链式定义:先算小计,再算折扣后金额,computed 之间也能互相依赖
按钮交互要防错和校验
用户点“+”“−”时,不能只改数量,还得考虑业务约束:
- 减号按钮加
:disabled="item.count ,禁用时不让点 - 加号前检查库存(假设有
item.stock),超限则提示而非静默失败 - 数量输入框失焦或回车时,自动修正异常值(比如负数、非数字、超过库存),再触发更新
选中状态与条件汇总也靠 computed
实际购物车常需“仅算已勾选商品”的总价,这时用两个 computed 协作:
const checkedItems = computed(() => cartItems.value.filter(item => item.checked))const checkedTotal = computed(() => checkedItems.value.reduce((s, i) => s + i.price * i.count, 0))- 全选/反选只需批量赋值
item.checked = true/false,两个计算属性自动联动更新
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!









