Home  >  Q&A  >  body text

javascript - vue listens to an item in an array in data

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?

女神的闺蜜爱上我女神的闺蜜爱上我2663 days ago747

reply all(2)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-07-05 11:01:38

    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)
      }
    }

    reply
    0
  • 怪我咯

    怪我咯2017-07-05 11:01:38

    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

    reply
    0
  • Cancelreply