watchEffect函数

watchEffect函数

  • watch的套路是:既要指明监视的属性,也要指明监视的回调。

  • watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性。

  • watchEffect有点像computed:

    • 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。

    • 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值

<template>
  <div class="about">
      <input type="text" v-model="phone.name1"> <br>
      <input type="text" v-model="phone.name2"> <br>
      <input type="text" v-model="phone.a.b.c">
  </div>
</template>
<script>
import { reactive, ref ,computed,watch ,watchEffect} from 'vue'
export default {
  setup(){  
    let phone = reactive({
        name1 : '小米',
        name2 : '红米',
        a:{
          b:{
            c:111
          }
        }
    })
    
    //watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
    watchEffect(()=>{
        const x1 = phone.name2
        const x2 = phone.name1
        const x3 = phone.a.b.c
        console.log('watchEffect配置的回调执行了')
    })

    return {phone}
  }
}
</script>

 

posted @ 2022-05-17 14:27  杨建鑫  阅读(243)  评论(0编辑  收藏  举报