The usage and difference between Computed and Watch in Vue

 Computed attributes (computed)

We all know that Vue is very convenient to use expressions in templates, such as { {message}}; in fact, Vue supports more complex logic, such as { {message+message1+message2}}, but vue suggests that we use an expression. If the logic of more than one expression is required, calculated attributes should be used .

Example

Such as: a=1, b=2, c=3, calculate a+b+c and display it on the page

Writing 1 (multiple expressions):

 <div id="example">
      <p>{
   
   {a+b+c}}</p>
 </div>
<script>
var vm = new Vue({
  el: '#example',
  data: {
    a: 1,
    b:2,
    c:3
  }
})
</script>

Writing 2 (calculated attributes):

<div id="example">
    <p>{
   
   {d}}</p>
</div>
<script>
var vm = new Vue({
  el: '#example',
  data: {
    a: 1,
    b:2,
    c:3
  },
  computed: {
    d: function () {
      return this.a + this.b+ this.c
    }
  }
})

</script>

Compare

1. Both of these two ways of writing can get the result we want;

2. The first type of multi-expression writing method will undoubtedly monitor the three attributes of a, b, and c and change with the attributes. The second type of calculation attribute d also depends on a, b, and c. When these three attributes are If changes occur, d will be updated accordingly.

3. This is just the simple logic here of a+b+c, so I don't see how much difference between the two, once too many logical operations will make the template complicated and difficult to maintain , and this conversion cannot be reused; When calculating attributes, the logic is simple and clear , easy to maintain, and easy to reuse .

Of course method can also be realized, yes, you must have thought of it too

The following example is to compare the use of calculated properties and methods together

  <div id="example">
        <p>计算属性第1次:{
   
   {d}}</p>
        <p>计算属性第2次:{
   
   {d}}</p>
        <p>计算属性第3次:{
   
   {d}}</p>
        <p>计算属性第4次:{
   
   {d}}</p>
        <p>方法调用第1次:{
   
   {modthod_d()}}</p>
        <p>方法调用第2次:{
   
   {modthod_d()}}</p>
        <p>方法调用第3次:{
   
   {modthod_d()}}</p>
        <p>方法调用第4次:{
   
   {modthod_d()}}</p>
    </div>
<script>
var vm = new Vue({
  el: '#example',
  data: { 
    a:1,
    b:2,
    c:3
  },
  methods:{
    modthod_d:function(){
        console.log('method_d')
        return this.a + this.b+ this.c
    }
  },
  computed: {
    d: function () {
        console.log('computed_d')
      return this.a + this.b+ this.c
    }
  }
})

</script>

Run into the browser and watch the output

Compare

  1. It can be called correctly, and if we change the dependency, it will be updated;
  2. Use method: execute the corresponding function several times after using it several times, so method_d is printed 4 times;
  3. Use calculated attributes: Because of the cache, if the dependent data has not changed, the function will only be executed once for multiple accesses, so computed_d is only printed once, because there is a cache after the first calculation, and there is no need to calculate it later;
  4. Calculated attributes can save some resources because of the existence of cache, and the performance will definitely be improved. Therefore, it is more recommended to use calculated attributes.

Setter getter for calculated properties

Under normal circumstances, we only use the getter property in the calculated property (as in the above examples), but it supports the setter property, as follows:

 <div id="example">
        <p>计算属性:{
   
   {d}}</p>
        <button @click="incre">set计算属性</button>
    </div>

<script>
var vm = new Vue({
  el: '#example',
  data: { 
    a:1,
    b:2,
    c:3,
    n:1
  },
  methods:{
    incre:function(){
        this.d=++this.n;
    }
  },
  computed: {
    d:{
       get:function () {
         console.log('computed_d')
         return this.a + this.b+ this.c
        },
        set:function(newVal){
            this.a=newVal;
        }

    } 
  }
})

Page effect

As in the above example, if we write set to the calculated attribute d, we can perform the desired operation through this.d.

Monitor attributes (watch)

Single attribute instance

<div id="example">
        <p>{
   
   {a}}</p>
        <button @click="mod_a">修改a</button>
    </div>
<script>
var vm = new Vue({
  el: '#example',
  data: { 
    a:1
  },
  methods:{
    mod_a:function(){
        this.a++;
    }
  },
  watch:{
    a:function(newVal,oldVal){
      console.log("新值:"+newVal+" 旧值:"+oldVal);
    }
  }
})

</script>

Page effect

Object monitoring instance (attribute monitoring one by one)

  <div id="example">
        <p>{
   
   {person}}</p>
        <input v-model="person.name">
    </div>

<script>
var vm = new Vue({
  el: '#example',
  data: { 
    a:1,
    person:{
      name:'张三',
      age:30
    }
  },
  methods:{
    mod_a:function(){
        this.a++;
    }
  },
  watch:{
    'person.name':function(newVal,oldVal){
      console.log("新值:"+newVal+" 旧值:"+oldVal);
    }
  }
})

</script>

have a test:

In-depth monitoring object (that is, you do not need to write monitoring for each attribute separately, and monitor all attributes of this object at once)

 <div id="example">
        <p>{
   
   {person}}</p>
        name:<input v-model="person.name"><br>
        age:<input v-model="person.age">
    </div>

<script>
var vm = new Vue({
  el: '#example',
  data: { 
    a:1,
    person:{
      name:'张三',
      age:30
    }
  },
  methods:{
    mod_a:function(){
        this.a++;
    }
  },
  watch:{
    person:{
       handler(newVal,oldVal) {
         console.log("新值:"+JSON.stringify(newVal)+" 旧值:"+JSON.stringify(oldVal));
      },
      deep: true
    }
  }
})

</script>

Page effect:

The difference between calculated attributes and attribute monitoring:

1. Calculated attribute variables are defined in computed, and attribute monitoring is defined in data.

2. The calculated attribute is a declarative description that a value depends on other values, and the DOM is recalculated after the dependent value changes. The attribute monitors the defined variable, and when the defined value changes, the corresponding function is executed.

 

There is no right or wrong choice and use of the two. I just hope that they can be used better, not abused. Personally, I prefer to use calculated attributes.

 

Guess you like

Origin blog.csdn.net/dkm123456/article/details/114885079