Store 的职责与响应式消费:练习答案
一种可验证的实现是把“不变量”写进 action,而不是让组件直接改数组:
ts
function remove(id: string) {
const index = items.value.findIndex((item) => item.id === id)
if (index >= 0) items.value.splice(index, 1)
}
function quantityOf(id: string) {
return items.value.find((item) => item.id === id)?.quantity ?? 0
}
function decrement(id: string) {
const item = items.value.find((entry) => entry.id === id)
if (!item) return
if (item.quantity === 1) remove(id)
else item.quantity -= 1
}输入 add({id:'a',price:10})、add({id:'a',price:10})、decrement('a') 后,quantityOf('a') 为 1、count 为 1、total 为 10;再次 decrement 后商品不存在,三个派生值分别为 0、0 和 0。remove('missing') 提前返回,因此不会制造无意义的数组变更。
答案只用于对照;请把自己的输入、输出和边界记录到项目实验日志中。