As shown in the figure, I want to monitor items.amount. In addition to the for loop, is there any simpler way to write it?
computed: { totalAmount () { // 计算出 items 数组中的 amount 总额 return this.items.reduce((a, b) => ({ amount: a.amount + b.amount })).amount } }, watch: { totalAmount (newVal) { // 当计算属性变更时触发更新 console.log('amount change to ', newVal) } }
Personally, I think your total money should be changed to a calculated attribute
computed: { money() { let sum = 0; this.items.forEach(item => { sum += item.amount; }); return sum; } }
Then delete the money attribute from data and delete your watch
Personally, I think your total money should be changed to a calculated attribute
Then delete the money attribute from data and delete your watch