Vue3-watch

164 阅读1分钟

watch

  • 和Vue2基本相似,配置是一样的
  • 两个坑:
    • 监视reactive定义的响应式数据时:oldVal无法正确的获取,强制开启了深度监视(deep配置无效)
    • 监视reactive定义的响应式数据中的某个属性(对象)时:deep配置有效
<template>
    <h1>{{num}}</h>
    <h1>{{msg}}</h>
</template>
<script>
import {ref,reactive,watch} from 'vue'
exprot default {
    name: 'App',
    setup() {
        let num = ref(0)
        let msg= ref('消息')
        let p = reactive({
            name: '景天',
            age: 18,
            a: {
                b: {
                    c: 100
                }
            }
        })
        
        // 1. 监视ref所定义的一个响应式数据
        watch(num,(newVal,oldVal)=> {
            console.log(newVal,oldVal)
        },{immediate:true})
        
         // 2. 监视ref所定义的多个响应式数据
        watch([num,msg],(newVal,oldVal)=> {
            console.log(newVal,oldVal)
        },{immediate:true})
        
        // 3. 监视reactive所定义的一个响应式数据。
        // 注意:此处无法正确的获得oldVal
        // 注意:强制开启了深度监视器(deep配置无效)
        watch(p,(newVal,oldVal)=> {
            console.log(newVal,oldVal)
        },{deep:false}) // 此处的deep无效
        
        // 4. 监视reactive所定义的一个响应式数据中的某个属性。需要使用函数
        watch(()=>p.name,(newVal,oldVal)=> {
            console.log(newVal,oldVal)
        })
        
        // 5. 监视reactive所定义的一个响应式数据中的某些属性。
        watch([()=>p.name,()=>p.age],(newVal,oldVal)=> {
            console.log(newVal,oldVal)
        },{deep:false})
        
        // 特殊情况
        watch(()=>p.a,(newVal,oldVal)=> {
            console.log(newVal,oldVal)
        },{deep:true})      // 此处由于监视的是reactive所定义的对象中的某个属性(对象),所以deep配置有效
        
        
        return {
            num,
            msg,
            p
        }
    }
}
</script>