Computed

Evaluated properties are generated by listening for changes in dependencies, which makes it necessary for evaluated properties to contain returns.

Calculated properties include two parts: GET and set. By default, only GET is available. Set needs to be added by itself

computed{
    fullname: {get: {return this.firstName+' ' +this.lastName
        }
        set:function(newName){
            let names = newName.splict( ' ')
            this.firstName = names[0]
            this.lastName = names[name.length-1]
        }
    }
}

vm.fullname = 'jack ma'The setter is called,thisThe firstName andthisThe.lastname changesCopy the code

Note that computed can be cached on properties, and when the dependencies have not changed, the cached results are still read and the code is not executed multiple times. And you can use the closure method to achieve the purpose of passing parameters.

:data="closure(item, itemName, blablaParams)"
computed: {
 closure () {
   return function (a, b, c) {
        /** do something */
        return data
    }
 }
}

Copy the code

Wathch

Listening properties is some logic that is made by listening for changes in properties.

<template>
  <div class="attr">
    <h1>Watch the attribute</h1>
    <h2>{{ $data }}</h2>
    <button @click="() => (a += 1)">Modify the value of a</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      a: 1.b: { c: 2.d: 3 },
      e: {
        f: {
          g: 4}},h: [].obj: { a: 1,}}; },watch: {
    a: function(val, oldVal) {
      this.b.c += 1;
    },
    "b.c": function(val, oldVal) {
      this.b.d += 1;
    },
    "b.d": function(val, oldVal) {
      this.e.f.g += 1;
    },
    e: {
      handler: function(val, oldVal) {
        this.h.push("jack");
      },
      deep: true // To listen for changes in the internal values of the e object}},obj: { 
       handler: function(newVal, oldVal) { 
           console.log(newVal);
           },
       deep: true.immediate: true}};</script>

Copy the code

If deep of e is false, then watch thinks that this.e.F.g +1 only changes g, but e does not change.

For obj, immediate is true, and the handler in OBj is triggered once the code is loaded

Comparison of the two

  • Watch: Monitors the property value, and whenever the property value changes, it triggers the execution of a callback function to perform a series of operations.
  • Computed: The dependent value is monitored. If the value remains unchanged, the value is directly read from the cache for reuse. If the value changes, the value is recalculated.

There is one important difference: computed properties cannot perform asynchronous tasks; computed properties must be executed synchronously. This means that the computed property cannot be requested from the server or performed as an asynchronous task. If you encounter an asynchronous task, give it to the listening property. Watch can also detect computed properties.