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、Person.vue代码如下:
<template> <div class="person"> <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" name="Person001" setup> 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, () =>person.car], (oldValue, onCleanup) => { console.log('car变了:原:', oldValue, '现在:', onCleanup) }, {deep: true}) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
3、效果如下:
标签:function,TypeScript,修改,car,10px,watch,person,vue,Vue3 From: https://www.cnblogs.com/tianpan2019/p/18365470