018、Vue3+TypeScript基础,使用watch监视reactive对象,默认是开启的深度监视,且无法关闭
01、App.vue代码如下:
<template> <div class="app"> <h2>{{ title }}</h2> <!-- 使用了ref来获取子组件的属性--> <Person/> </div> </template> <script lang="ts" setup name="App"> // JS或TS import Person from './view/Person.vue' import {ref} from 'vue' let title = ref('好好学习,天天向上') </script> <!--样式 scoped表示仅本单元有效--> <style scoped> .app { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; } </style>
02、代码如下:
<template> <div class="person"> <h1>情况二:监视【ref】定义的【基本类型】数据</h1> <h2>姓名:{{ person.name }}</h2> <h2>年龄:{{ person.age }}</h2> <button @click="changeName">修改名字</button> <button @click="changeAge">修改年龄</button> <button @click="changePerson">修改整个人</button> <hr> <h2>测试:{{ obj.a.b.c }}</h2> <button @click="changeObj">修改obj.a.b.c</button> </div> </template> <script lang="ts" name="Person001" setup> import {reactive, watch} from 'vue' let person = reactive({ name: '张三', age: 18 }) let obj = reactive({ a: { b: { c: 100 } } }) function changeName() { person.name = '李四'; } function changeAge() { person.age += 1; } function changePerson() { Object.assign(person, {name: '王五', age: 20}); } function changeObj() { obj.a.b.c += 1; } // 监视person变化, deep:true表示深度监视,immediate:true表示立即执行 watch(person, (newVal, oldVal) => { console.log('person变化了,由', oldVal, '变为:', newVal); }, {deep: true, immediate: true}) // 如果是监视的reactive对象,默认是开启的深度监视,且无法关闭 watch(obj, (newVal, oldVal) => { console.log('obj变化了,由', oldVal, '变为:', newVal); }) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
03、效果如下: