javascript - What is the difference between computed and watch in vue?
高洛峰
高洛峰 2017-05-19 10:24:39
0
4
569

As the title says, see an example of computed and watch getting the full name in the vue.js official document:

var 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
    }
  }
})
var var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

The rookie said that he doesn’t understand the difference between them. Can’t watch be obtained like computed?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
洪涛

You write less code using computed, there is no major difference

大家讲道理

I think there is still a difference, and the two application situations should be distinguished.

Computed properties are computed properties and observations are observations.

As the name suggests, a calculated attribute is another attribute calculated through other variables. fullName recalculates its own value when the two variables it depends on, firstName and lastName, change.

Also, Computed properties have caching. Computed properties are cached based on their dependencies. A computed property is only re-evaluated when its associated dependencies change. This means that as long as neither lastName nor firstName has changed, multiple accesses to the fullName calculated property will immediately return the previous calculated result without having to execute the function again.

Observing watch is to observe a specific value and execute a specific function when the value changes. For example, in the paging component, we can detect the page number and execute the function to obtain data.

You can check the document in more detail: https://cn.vuejs.org/v2/guide...

某草草

More readable and generally less code.

为情所困

Simply speaking, computed is based on cache, and watch is equal to a function. Personally, I think it’s enough as long as you know how to use it. I’ll tell you the specific differences

I think computed attributes should be used more widely

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template