提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.6 KiB

  1. watch
  2. 监视`ref`定义的对象类型数据直接写数据名监视的是对象的地址值
  3. 若想监视对象内部的数据要手动开启深度监视
  4. 注意
  5. * 若修改的是`ref`定义的对象中的属性`newValue` `oldValue` 都是新值因为它们是同一个对象
  6. * 若修改整个`ref`定义的对象`newValue` 是新值 `oldValue` 是旧值因为不是同一个对象了
  7. /*
  8. 监视情况一监视ref定义的对象类型数据监视的是对象的地址值若想监视对象内部属性的变化需要手动开启深度监视
  9. watch的第一个参数是被监视的数据
  10. watch的第二个参数是监视的回调
  11. watch的第三个参数是配置对象deepimmediate等等.....
  12. */
  13. watch(person,(newValue,oldValue)=>{
  14. console.log('person变化了',newValue,oldValue)
  15. },{deep:true})
  16. 如果加immediate:true则初始化时就会立即执行一次回调函数
  17. <template>
  18. <div class="person">
  19. <h1>情况四监视refreactive定义的对象类型数据中的某个属性</h1>
  20. <h2>姓名{{ person.name }}</h2>
  21. <h2>年龄{{ person.age }}</h2>
  22. <h2>汽车{{ person.car.c1 }}{{ person.car.c2 }}</h2>
  23. <button @click="changeName">修改名字</button>
  24. <button @click="changeAge">修改年龄</button>
  25. <button @click="changeC1">修改第一台车</button>
  26. <button @click="changeC2">修改第二台车</button>
  27. <button @click="changeCar">修改整个车</button>
  28. </div>
  29. </template>
  30. <script lang="ts" setup name="Person">
  31. import {reactive,watch} from 'vue'
  32. // 数据
  33. let person = reactive({
  34. name:'张三',
  35. age:18,
  36. car:{
  37. c1:'奔驰',
  38. c2:'宝马'
  39. }
  40. })
  41. // 方法
  42. function changeName(){
  43. person.name += '~'
  44. }
  45. function changeAge(){
  46. person.age += 1
  47. }
  48. function changeC1(){
  49. person.car.c1 = '奥迪'
  50. }
  51. function changeC2(){
  52. person.car.c2 = '大众'
  53. }
  54. function changeCar(){
  55. person.car = {c1:'雅迪',c2:'爱玛'}
  56. }
  57. // 监视,情况四:监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式
  58. /* watch(()=> person.name,(newValue,oldValue)=>{
  59. console.log('person.name变化了',newValue,oldValue)
  60. }) */
  61. // 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
  62. watch(()=>person.car,(newValue,oldValue)=>{
  63. console.log('person.car变化了',newValue,oldValue)
  64. },{deep:true})
  65. </script>