The difference between computed and watch, methods, and the use of scene!

table of Contents

Requirements: After calculation / processing based on price, quantity, discount amount based on the total amount;

export default {
  data() {
    return {
      discounts: 50, //优惠券
      Money: null, //单价
      Num: null, //数量
      Total: 0 //合计
    };
  },
};

At this time there are at least four ways to achieve, it is easy to interpolation expression, computed (calculated property), watch (listeners), methons (method) with four Hunzhuo; 

computed (calculated properties) achieved:

export default {
  data() {
    return {
      discounts: 50, //优惠券
      Money: null, //单价
      Num: null //数量
      //   Total: 0 //合计
    };
  },
  computed: {
    Total() {
      if (!this.Money || !this.Num) return 0;
      return this.Money * this.Num - this.discounts >= this.discounts ? this.Money * this.Num - this.discounts:0;
    }
  }
};

computed (calculated attributes) VS methods (Method):

methods:{
    Total() {
      if (!this.Money || !this.Num) return 0;
      return this.Money * this.Num - this.discounts >= this.discounts ? this.Money * this.Num - this.discounts:0;
    }
  }

The final results of the two methods is indeed identical. However, the difference is calculated based on their properties are dependent responsive caching . It will only amount to calculate the total value in the unit price / quantity changes. This means that as long as the Money / Num has not changed, many visits Total calculate property returns before the results immediately, without having to perform functions again. But the method will be called again each time you re-rendering!

 computed (calculated attributes) VS watch (listeners):

export default {
  data() {
    return {
      discounts: 50, //优惠券
      Money: null, //单价
      Num: null, //数量
      Total: 0 //合计
    };
  },
  watch:{
      Money(){  //监听单价
         this.Total = this.Money * this.Num - this.discounts >= this.discounts ? this.Money * this.Num - this.discounts:0;
      },
      Num(){   //监听数量
         this.Total = this.Money * this.Num - this.discounts >= this.discounts ? this.Money * this.Num - this.discounts:0;
      }
  },
};

First, the use of more complicated wording of the listener, followed by terms of performance, the listener overhead is relatively large, watch usually handled / monitor more complex object properties, the easiest to understand is that when a data affect multiple data time watch is the best choice!

Published 17 original articles · won praise 76 · views 9659

Guess you like

Origin blog.csdn.net/qq_43471802/article/details/102654249