What is the difference between computed and watch?

Reference: The difference between computed and watch

1. Watch: One data affects multiple data

2. Computed: One data is affected by multiple data

3. The difference between watch computed methods

(1) Watch computed is based on Vue's dependency tracking mechanism. As long as the dependent data changes, all "related" data that depends on this data will "automatically" change, that is, automatically call related functions to achieve data changes
(2) The functions defined in methods need to be called manually to execute

4. Examples

new Vue({
  el: '#app',
  // 设置两个button,点击分别调用getMethodsDate,getComputedDate方法
  template: 
'<div id="app">
    <button @click="getMethodsDate">methods</button>
    <button @click="getComputedDate">computed</button>
</div>',
  methods: {
    getMethodsDate: function () {
      alert(new Date())
    },
    // 返回computed选项中设置的计算属性——computedDate
    getComputedDate: function () {
      alert(this.computedDate)
    }
  },
  computed: {
    computedDate: function () {
      return new Date()
    }
  }
  1. The return time of the two click methods is different
  2. Note that the time to return from two clicks of computed is the same, because computed provides the cached value at this time, and there is no recalculation of the calculated
    conditions for recalculation:
  3. There are dependent data (instance data placed under objects such as data)
  4. Dependent on data changes

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108272360