引入
vue 的数据监视可以进行数据检测但是要进行数据的引入
import { watch } from 'vue'
参数配置
一共分为三个参数配置分别为 数据 执行方法 执行条件
watch(()=> dog.age ,(newValue,oldValue)=> { console.log(newValue) console.log(oldValue)},{
deep:true,
immediate:true,
}
)
参数配置
depp: true ,开启深度监视,如果监视为对象属性会强行开启深度监视,如果是对象里面的对象 需要手动开启数据的监视
immediate 是否初开始进行监视
数据监听普通的数据
watch(peoper,(oldvalue,newValue)=> {
console.log(oldvalue,"oldvalue")
console.log(newValue,"newValue")
})
watch([peoper],(oldvalue,newValue)=> {
console.log(oldvalue,"oldvalue")
console.log(newValue,"newValue")
})
监听对象属性
watch(()=> dog.age ,(newValue,oldValue)=> {
console.log(newValue)
console.log(oldValue)
},{
deep:true,
immediate:true,
}
)
强调一定不要把第一个参数写{}不然不会生效
数据清理机制
watch(id, async (newId, oldId, onCleanup) => {
const { response, cancel } = doAsyncWork(newId)
// 当 `id` 变化时,`cancel` 将被调用,
// 取消之前的未完成的请求
onCleanup(cancel)
data.value = await response
})
关闭数据监听
const stop = watch(source, callback) // 当已不再需要该侦听器时: stop()
Vue官方文档 响应式 API:核心 | Vue.js