Vue3-watchEffect函数

189 阅读1分钟

watchEffect函数

  • watch:需要指明监视的属性,也要指明监视的回调
  • watchEffect:不需要指明监视哪个属性,监视的回调中用到哪个属性,就监视那个属性
  • watchEffect有点类似于computed:
    • computed注重的是计算出来的值,所以必须写返回值
    • watchEffect更注重的是过程,所以不需要写返回值
<template>
    <h1>{{num}}</h>
    <h1>{{msg}}</h>
</template>
<script>
import {ref,reactive,watchEffect} from 'vue'
exprot default {
    name: 'App',
    setup() {
        let num = ref(0)
        let msg= ref('消息')
        let p = reactive({
            name: '景天',
            age: 18,
            a: {
                b: {
                    c: 100
                }
            }
        })
        
        watchEffect(()=> {
            const x1 = sum.value
            const x2 = age.value
            console.log('watchEffect调用了')
        })
        
        return {
            num,
            msg,
            p
        }
    }
}
</script>