The difference between computed and watch examples in Vue

computedExample

<template>
  <div class="box">
    <input type="text" v-model="keyCode" placeholder="筛选" />
    <ul>
      <li v-for="(item, index) in filterCode" :key="index">{
   
   { item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      keyCode: "",
      list: ["apple", "huawei", "sony", "oppo", "vivo"],
    };
  },
  computed: {
     
     
    filterCode() {
     
     
      var arr = [];
      for (let i in this.list) {
     
     
        if (this.list[i].indexOf(this.keyCode) != -1) {
     
     
          arr.push(this.list[i]);
        }
      }
      return arr;
    },
  },
};
</script>

watchExample

<template>
  <div class="box">
    <input type="text" v-model="firstName" placeholder="" />
    <input type="text" v-model="lastName" placeholder="" />
    {
   
   { fullName }}
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      firstName: "",
      lastName: "",
      fullName: "",
    };
  },
  watch: {
     
     
    firstName(value) {
     
     
      this.fullName = `${
       
       value}${
       
       this.lastName}`;
    },
    lastName(value) {
     
     
      this.fullName = `${
       
       this.firstName}${
       
       value}`;
    },
  },
};
</script>

computed

  1. Rely on data cache, only execute when the data changes
  2. Asynchronous is not supported. It is invalid when there are asynchronous operations in the computed, and it is impossible to monitor data changes.
  3. Variables do not need to be defined in the data function

watch

  1. Support asynchronous operation of data changes
  2. Receive two parameters, the first parameter is the latest value; the second parameter is the value before the input
  3. The monitoring data must be the data in the props declared in the data or passed by the parent component
  4. Incur a large performance overhead

Guess you like

Origin blog.csdn.net/AK852369/article/details/114792154