1.在页面中引用watch
import {reactive,watch, ref} from 'vue'
2.在setup函数中使用watch监听ref定义的数据
//监听ref所定义的一个数据 newValue改变后新数据,变化前的旧数据 watch(sum,(newValue,oldValue)=>{ console.log('sum is changed',newValue,oldValue); },{immediate:true}) //immediate 立即执行
监听多个数据
//监听ref所定义的多个数据 watch([sum,msg],(newValue,oldValue)=>{ console.log('sum and msg is changed',newValue,oldValue); })
newValue和oldValue里数组的值和 [sum,msg] 的顺序是对应的
3.监听reactive所定义的响应式数据
<template> <!-- vue3中模版结构可以没有根标签 --> <div>姓名:{{person.name}}</div> <div>年龄:{{person.age}}</div> <div>薪水:{{person.job.j1.salary}}k</div> <button @click="person.name = '张三'">改名</button> <button @click="person.age++">增龄</button> <button @click="person.job.j1.salary++">涨薪</button> </template>
<script> // import { h } from 'vue' import {reactive,watch, ref} from 'vue' export default { components: { demo }, name: 'App', setup(){ let sum = ref(0) let msg = ref('hello boys') let person = reactive({ name:'章三', age:18, job:{ j1:{ salary:20 } } }) //监听reactive所定义的一个响应式数据的全部属性 // 注意1.此处无法正确获取oldvalue // 注意2.默认强制开启了深度监听,配置deep:false无效 当前使用的vue版本3.2.20 vue/cli 4.5.15 watch(person,(newValue,oldValue)=>{ console.log('person is changed',newValue,oldValue); }) //监听reactive所定义的一个响应式数据的某个属性 watch(()=>person.name,(newValue,oldValue)=>{ console.log('person.name is changed',newValue,oldValue); }) //监听reactive所定义的一个响应式数据的某些属性 watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{ console.log('person.name person.age is changed',newValue,oldValue); }) //特殊情况 监听响应式数据里的某个对象的属性需要配置deep watch(()=>person.job,(newValue,oldValue)=>{ console.log('person.job is changed',newValue,oldValue) },{deep:true}) return { data, // total, // fullName sum, msg, person } } } </script>
watchEffect
//不用指明监视的某个属性,监视的回调中用到哪个属性,那就监视哪个属性 watchEffect(()=>{ const x1 = person.job.j1.salary const x2 = sum.value console.log(' watcheffet回调执行了',x1,x2); })
watchEffect有点像computed,
computed注重值(回调函数的返回值),所有必须要写返回值
wacthEffect更注重过程(回调函数的函数体),所以不用写返回值,只要函数体内某个属性发生了变化,就重新走一遍流程。