文章詳情頁
javascript - vue監聽data中的某一數組的某一項
瀏覽:35日期:2023-02-27 13:59:21
問題描述
如圖我要監聽items.amount,除了for循環的寫法,還有什么更簡單的寫法嗎?
問題解答
回答1: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) }}回答2:
個人覺得,你的總額的money應該改成一個計算屬性
computed: { money() { let sum = 0; this.items.forEach(item => { sum += item.amount; }); return sum; }}
然后將money屬性從data中刪除,同時刪除你的watch
標簽:
JavaScript
相關文章:
排行榜
