主要结构
import {ref, reactive,watch} from 'vue'
watch([监听值1,监听2,...],(newVal,oldVal)=>{
...
},{
deep:true, //ref需要手动开启,reactive则不用主动开启 源码中是默认开启的
immediate:true, //默认一进来就开启执行一次
flush:'pre' //pre-组件更新之前调用 sync-同步执行 post-组件更新之后执行
)
具体写法
<template>
<div>
case1:<input v-model="name"/>
</div>
<div>
case2:<input v-model="name2"/>
</div>
<div>
深度监听:<input v-model="deep.child.inner.num"/><br>
深度监听单个属性:<input v-model="deep2.child.name"/>
</div>
</template>
<script setup lang='ts'>
import {ref, reactive,watch} from 'vue'
let name = ref<string>('youyunxia')
let name2 = ref<string>('张三')
/**
* 监听name
* 监听多个数据源要传数组[]
* watch([p1,p2,...],(newVal,oldVal)=>{})
*/
watch(name,(newVal,oldVal)=>{
console.log(newVal,oldVal)
})
watch([name,name2],(newVal,oldVal)=>{
console.log(newVal,oldVal)
})
/**
* 开启深度监听
* reactive不需要开启deep:true
* ref需要开启deep:true,但是返回的新值和旧值是一样的
* 多层嵌套的情况最好使用reactive
*/
let deep = reactive({
name:'youyunxia',
child:{
name:'child',
inner:{
num:3
}
}
})
watch(deep,(newVal,oldVal)=>{
console.log(newVal,oldVal)
},{
deep:true, //ref需要手动开启,reactive则不用主动开启 源码中是默认开启的
immediate:true, //默认一进来就开启执行一次
flush:'pre' //pre-组件更新之前调用 sync-同步执行 post-组件更新之后执行
})
/**
* 监听内部单个属性
* 只有使用reactive的时候,才可以监听到内部的单个属性
* 第一个参数格式为proxy对象,直接.写属性不对,官方推荐用一个箭头函数的形式转一下
* 例:()=> deep2.child.name
*/
let deep2 = reactive({
child:{
name:'child',
inner:{
num:3
}
}
})
watch( ()=> deep2.child.name,(newVal,oldValue)=>{
console.log(newVal,oldValue)
})
</script>
<style>
</style>