017、Vue3+TypeScript基础,使用watch监视时通过deep和immediate进行深度监视和立即执行
1、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>
2、效果如下:
<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> </div> </template> <script lang="ts" name="Person001" setup> import {ref, watch} from 'vue' let person = ref({ name: '张三', age: 18 }) function changeName() { person.value.name = '李四'; } function changeAge() { person.value.age += 1; } function changePerson() { person.value = {name: '王五', age: 20} } // 监视person变化, deep:true表示深度监视,immediate:true表示立即执行 watch(person, (newVal, oldVal) => { console.log('person变化了,由', oldVal, '变为:', newVal); }, {deep: true, immediate: true}) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
3、习惯如下: