What is the difference between watch and watchEffect?

Same point

1. Both can monitor data attribute changes.
2. Watch and watchEffect have the same behavior in terms of manually stopping listening, clearing side effects (passing onInvalidate as the third parameter to the callback), refresh timing and debugging.

the difference

1. Watch needs to clearly monitor which attribute
2. watchEffect will automatically monitor its changes based on the attributes
3. When watcheffect is initialized, it will definitely be executed once (collect the data to be monitored, otherwise you will not know what is being monitored), watch only has you It will only listen if initialization monitoring is set.

  const numberRef = ref(100)
  const state = reactive({
    
    
      name: 'test',
      age: 20
   })

watch:

       watch(numberRef, (newNumber, oldNumber) => {
    
    
            console.log('ref watch', newNumber, oldNumber)
        }
        , {
    
    
            immediate: true // 初始化之前就监听,可选
        }
        )

        setTimeout(() => {
    
    
            numberRef.value = 200
        }, 1500)

        watch(
            // 第一个参数,确定要监听哪个属性
            () => state.age,

            // 第二个参数,回调函数
            (newAge, oldAge) => {
    
    
                console.log('state watch', newAge, oldAge)
            },

            // 第三个参数,配置项
            {
    
    
                immediate: true, // 初始化之前就监听,可选
                // deep: true // 深度监听
            }
        )

        setTimeout(() => {
    
    
            state.age = 25
        }, 1500)
        setTimeout(() => {
    
    
            state.name = 'testA'
        }, 3000)

watchEffect

watchEffect(() => {
    
    
            // 初始化时,一定会执行一次(收集要监听的数据)
            console.log('hello watchEffect')
        })
        watchEffect(() => {
    
    
            // 监听的是state.name 不会监听state.age
            console.log('state.name', state.name)
        })
        watchEffect(() => {
    
    
            console.log('state.age', state.age)
        })
        watchEffect(() => {
    
    
            console.log('state.age', state.age)
            console.log('state.name', state.name)
        })
        setTimeout(() => {
    
    
            state.age = 25
        }, 1500)
        setTimeout(() => {
    
    
            state.name = 'test1'
        }, 3000)

Guess you like

Origin blog.csdn.net/qq_53509791/article/details/130924263