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.
|
|
watch监视`ref`定义的【对象类型】数据:直接写数据名,监视的是对象的【地址值】若想监视对象内部的数据,要手动开启深度监视。
注意:* 若修改的是`ref`定义的对象中的属性,`newValue` 和 `oldValue` 都是新值,因为它们是同一个对象。* 若修改整个`ref`定义的对象,`newValue` 是新值, `oldValue` 是旧值,因为不是同一个对象了。 /* 监视,情况一:监视【ref】定义的【对象类型】数据,监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视 watch的第一个参数是:被监视的数据 watch的第二个参数是:监视的回调 watch的第三个参数是:配置对象(deep、immediate等等.....) */ watch(person,(newValue,oldValue)=>{ console.log('person变化了',newValue,oldValue) },{deep:true}) 如果加immediate:true,则初始化时就会立即执行一次回调函数
<template> <div class="person"> <h1>情况四:监视【ref】或【reactive】定义的【对象类型】数据中的某个属性</h1> <h2>姓名:{{ person.name }}</h2> <h2>年龄:{{ person.age }}</h2> <h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2> <button @click="changeName">修改名字</button> <button @click="changeAge">修改年龄</button> <button @click="changeC1">修改第一台车</button> <button @click="changeC2">修改第二台车</button> <button @click="changeCar">修改整个车</button> </div></template>
<script lang="ts" setup name="Person"> import {reactive,watch} from 'vue'
// 数据
let person = reactive({ name:'张三', age:18, car:{ c1:'奔驰', c2:'宝马' } }) // 方法
function changeName(){ person.name += '~' } function changeAge(){ person.age += 1 } function changeC1(){ person.car.c1 = '奥迪' } function changeC2(){ person.car.c2 = '大众' } function changeCar(){ person.car = {c1:'雅迪',c2:'爱玛'} }
// 监视,情况四:监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式
/* watch(()=> person.name,(newValue,oldValue)=>{ console.log('person.name变化了',newValue,oldValue) }) */
// 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
watch(()=>person.car,(newValue,oldValue)=>{ console.log('person.car变化了',newValue,oldValue) },{deep:true})</script>
|