作用:侦听一个或多个响应式数据的变化,数据变化时执行回调函数

两个额外参数:1. immediate(立即执行)  2.deep(深度监听)

immediate:在侦听器创建时立即触发回调,响应式数据变化之后继续执行回调

deep: 默认机制:通过watch监听的ref对象默认是浅层监听的,直接修改嵌套的对象属性不会触发回调函数,需要开启deep选项

1.导入watch函数

2. 执行watch函数传入要侦听的响应式数据(ref对象)和回调函数

监听单个数据:
 <!--监听器watch函数-->
<script setup>
// 导入watch函数
import {ref,watch} from "vue";
const count = ref(0)
const setCount = ()=>{
    count.value++
}
// watch 侦听单个数据
// watch函数里ref不需要加.value  watch会自动读取
watch(count,(newValue,oldValue)=>{
    console.log('count变化了',newValue,oldValue)
})
</script>

<template>
    <div>
        <button @click="setCount">原始响应数据 {{ count }}</button>
    </div>
</template>
监听多个数据:
<script setup>
import {ref,watch} from "vue";
const count =ref(0)
const setCount = ()=>{
    count.value++
}
const name =ref(0)
const changeName =()=>{
    name.value='pc'
}
watch(
    [count,name],([newCount,oldCount],[newName,oldName])=>{
        console.log('count或name变化了',[newCount,oldCount],[newName,oldName])
    }
)
</script>

<template>
    <div>
        <button @click="setCount">修改count {{ count }}</button>
        <button @click="changeName">修改name {{ name }}</button>
    </div>
</template>
immediate使用:
<script setup>
import {ref,watch} from "vue";
const count = ref(0)
const setCount =()=>{
    count.value++
}
watch(count,()=>{
    console.log('count变化了')
},{
    immediate:true
})
</script>
<template>
    <div>
        <button @click="setCount">修改count {{ count }}</button>
    </div>
</template>
deep使用:对象的所有属性都会监听到

 若只想侦听对象的某个单一属性,可以把第一个参数写成函数的写法,返回要监听的具体属性,如下:

<script setup>
import {ref, watch} from "vue"
const state = ref({
    name: 'hi',
    age: 18
})
const changeName = () => {
    state.value.name = 'hello'
}
const changeAge = () => {
    state.value.age++
}
watch(
    ()=>state.value.age,
    ()=>{
        console.log('age变化了')
    }
)
</script>
<template>
    <div>
        <button @click="changeName">修改name {{ state.name }}</button>
        <button @click="changeAge">修改age {{ state.age }}</button>
    </div>
</template>

Logo

前往低代码交流专区

更多推荐