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更注重過程(回調函數的函數體),所以不用寫返回值,只要函數體內某個屬性發生了變化,就重新走一遍流程。