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、習慣如下: