jannahuang / blog

MIT License
0 stars 0 forks source link

Vue Computed 和 Watch 的区别 #23

Open jannahuang opened 2 years ago

jannahuang commented 2 years ago

Computed 计算属性

类型:{ [key: string]: Function | { get: Function, set: Function } } 详细: 计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。 注意如果为一个计算属性使用了箭头函数,则 this 不会指向这个组件的实例。 举例:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    // 计算属性的 getter
    fullName: function () {
      // `this` 指向 vm 实例
      return this.firstName + ' ' + this.lastName
    }
  }
})

在上例中,为计算属性 fullName 提供的函数将用作其 getter 函数。vm.fullName 依赖于 vm.firstName 和 vm.lastName,因此当 vm.firstName 或 vm.lastName 发生改变时,vm.fullName 也会更新。

Computed 对比 Methods

当然上述结果也可以通过调用 methods 方法来实现:

<p>fullName: "{{ fullName() }}"</p>
...
methods: {
  fullName: function () {
    return this.firstName + ' ' + this.lastName
  }
}

不同的是计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。计算属性的结果会被缓存,除非依赖的响应式 property 变化才会重新计算。 在上例中,意味着只要 firstName 和 lastName 还没有发生改变,多次访问 fullName 计算属性会立即返回之前的计算结果,而不必再次执行函数。 而使用 methods 方法的话,会再次执行函数。

Computed 的 setter

计算属性默认只有 getter,不过在需要时也可以添加 setter。

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

Watch 侦听器

类型:{ [key: string]: string | Function | Object | Array } 详细: 一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个 property。

上例改为用 watch 实现:

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

可以明显看出上例中,使用 computed 会更合适。 大多数情况下优先使用计算属性,watch 更适用于需要在数据变化时执行异步或开销较大的操作。 举例:

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
...
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
  el: '#watch-example',
  data: {
    question: '',
    answer: 'I cannot give you an answer until you ask a question!'
  },
  watch: {
    // 如果 `question` 发生改变,这个函数就会运行
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
    // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
    // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
    // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
    // 请参考:https://lodash.com/docs#debounce
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    getAnswer: function () {
      if (this.question.indexOf('?') === -1) {
        this.answer = 'Questions usually contain a question mark. ;-)'
        return
      }
      this.answer = 'Thinking...'
      var vm = this
      axios.get('https://yesno.wtf/api')
        .then(function (response) {
          vm.answer = _.capitalize(response.data.answer)
        })
        .catch(function (error) {
          vm.answer = 'Error! Could not reach the API. ' + error
        })
    }
  }
})
</script>

在这个示例中,使用 watch 选项允许我们执行异步操作 (访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的。

区别总结

  1. 在语义上,computed 是计算,watch 是侦听。
  2. computed 适用于依赖其他一个或多个属性计算得来的属性;watch 适用于当一个属性发生变化时,需要执行对应的操作。
  3. computed 支持缓存,只有依赖数据发生改变,才会重新进行计算;watch 不支持缓存,数据变化,直接会触发相应的操作。
  4. computed 不支持异步;watch 支持异步,适用于在数据变化时执行异步或开销较大的操作。

以上笔记参考vue官方文档