The difference between computed and watch

One, computed and watch

In the previous exercise, I encountered computed to monitor a certain data change. We all know that both computed and watch can monitor data changes, but how to distinguish them?

1.1 watch

1.1.1 Simple execution of watch

<template>
  <div class="stylebg">
    <div class="mt22">
      watch的运用
    </div>
    <div>
      姓:<el-input v-model="firstName"></el-input>
    </div>
    <div>
      名:<el-input v-model="secondName"></el-input>
    </div>
    <div>
      {
   
   {fullName}}
    </div>
  </div>
</template>

<script>
export default {
      
      
  data(){
      
      
    return{
      
      
      firstName:'1',
      secondName:'2',
      fullName:''
    }
  },
  watch:{
      
      
     firstName(fValue){
      
      
       console.log('执行了watch')
       this.fullName = fValue + this.secondName
     },
    secondName(sValue){
      
      
      this.fullName = this.firstName + sValue
    },
  }
}
</script>

<style scoped>
  .mt22{
      
      
    margin:22px 0;
  }
</style>

run screenshot
insert image description here

1.2.1 Features of watch

According to the above code, we can summarize the following five characteristics of watch:

  1. Listen to one data, one attribute affects multiple attributes
  2. Return without return
  3. The first loading will not listen to the attribute name in the watch
  4. Support asynchronous operation, you can monitor asynchronous
  5. does not support caching

1.3.1 The first loading of watch

From the code running in 1.2 above, it can be concluded that when we load the page for the first time, the watch will not monitor the attribute name in the watch, so is there a way to get in touch with this limitation? Further explanation will be given in 1.3.1

1.3.1.1 How to realize the first loading of watch

We further improved the code of 1.2. We need to define the immediate:true related attribute in the attribute name, and then write the latest value assigned to the internal attribute method handler( ), so that the listener can be loaded for the first time. An attribute name of watch.

<template>
  <div class="stylebg">
    <div class="mt22">
      watch的运用
    </div>
    <div>
      姓:<el-input v-model="firstName"></el-input>
    </div>
    <div>
      名:<el-input v-model="secondName"></el-input>
    </div>
    <div>
      {
   
   {fullName}}
    </div>
  </div>
</template>

<script>
export default {
      
      
  data(){
      
      
    return{
      
      
      firstName:'1',
      secondName:'2',
      fullName:'',
    }
  },
  watch:{
      
      
    firstName: {
      
      
        // 监听数据
      handler(fValue) {
      
      
          console.log('执行了watch')
          this.fullName = fValue + this.secondName
      },
      deep: true, // 深度监听
      immediate:true, //当 watch 一个变量的时候,初始化时并不会执行你需要在created的时候手动调用一次。添加immediate属性,这样初始化的时候也会触发
    },

    secondName(sValue){
      
      
      this.fullName = this.firstName + sValue
    }
  }

}
</script>

<style scoped>
  .mt22{
      
      
    margin:22px 0;
  }
</style>

run screenshot
insert image description here

From the running screenshot, we can see that when the page is loaded for the first time, the internal code in the firstName attribute name will be executed (it can be seen from the string of 'executed watch' printed on the console and the string of fullname displayed on the interface)

2.1 computed

2.1.1 simple operation of computed

<template>
  <div class="stylebg">
    <div class="mt22">
      computed的运用
    </div>
    <div>
      姓:<el-input v-model="firstName2"></el-input>
    </div>
    <div>
      名:<el-input v-model="secondName2"></el-input>
    </div>
    <div>
      {
   
   {fullName2}}
    </div>
  </div>
</template>

<script>
export default {
      
      
  data(){
      
      
    return{
      
      
      firstName2:'1',
      secondName2:'2',
      // fullName2:''
    }
  },
  computed:{
      
      
    fullName2(){
      
      
      console.log('执行了computed')
      return this.firstName2 + this.secondName2
    }
  },
}
</script>

<style scoped>
  .mt22{
      
      
    margin:22px 0;
  }
</style>

run screenshot
insert image description here

2.2.1 Features of computed

According to the above code, we can summarize the following five characteristics of computed:

  1. Listen to multiple data, and multiple attributes affect one attribute
  2. Must use return to return
  3. The first loading will listen to the attribute name in computed
  4. Cannot support asynchronous operations, neither can monitor data changes in asynchronous operations
  5. Supports caching to avoid the need to recalculate every time a value is fetched.

2.2.2 The problem of setting attribute names in computed

I encountered a problem in writing the code, because computed will return the calculated value directly to the variable fullName2 at runtime, and there is an empty string of fullName2 in data at the same time, an error will occur when the code is executed, then Why does this error occur? It mainly involves the renaming of attribute names.

2.2.2.1 Why can't the attributes in data and compted be redefined, and an error will be reported?

In the execution of hanging data in the vm instance, the following vue source code will be referred to

 	function initState (vm) {
    
    
       vm._watchers = [];
       var opts = vm.$options;
       if (opts.props) {
    
     initProps(vm, opts.props); }
       if (opts.methods) {
    
     initMethods(vm, opts.methods); }
       if (opts.data) {
    
    
         initData(vm);
       } else {
    
    
         observe(vm._data = {
    
    }, true /* asRootData */);
       }
       if (opts.computed) {
    
     initComputed(vm, opts.computed); }
       if (opts.watch && opts.watch !== nativeWatch) {
    
    
         initWatch(vm, opts.watch);
       }
     }

It can be seen from the above that the code will mount props and other methods on the vm instance, and the execution sequence is props→methods→data→computed→watch. So if the attribute names are the same, the latter value will overwrite the previous value. In actual operation, an error of attribute name renaming will be thrown directly.
When writing code, it is necessary to avoid repeated writing of attribute names.

2. The difference between computed and watch

After the introduction of the operation of computed and watch in the first chapter, the differences between them can be listed:

watch computed
Listen to one data, one attribute affects multiple attributes Listen to multiple data, and multiple attributes affect one attribute
Return without return Must use return to return
The first loading will not listen to the attribute name in the watch (when immediate:true is not set) The first loading will listen to the attribute name in computed
Support asynchronous operation, you can monitor asynchronous Cannot support asynchronous operations, neither can monitor data changes in asynchronous operations
does not support caching Supports caching to avoid the need to recalculate every time a value is fetched.

3. Scenarios commonly used by computed and watch

watch: For asynchronous operations or high-cost scenarios, inputting a string in the search box will call the API to dynamically obtain the corresponding data list.
computed: If multiple items are checked in the shopping cart, check the price attribute of each item to affect the attribute of the total price.

Guess you like

Origin blog.csdn.net/Ak47a7/article/details/130138163