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"> 姓:<input type="text" v-model="firstName"/><br> 名:<input type="text" v-model="lastName"/><br> 全名<span>{{ fullName }}</span><br> 全名<span>{{ fullName }}</span><br> </div> </template> <script lang="ts" name="Person001" setup> import {computed, ref} from 'vue' let firstName = ref('') let lastName = ref('') //計算屬性,計算屬性的結果會被快取,只有當依賴發生改變時,計算屬性才會重新計算。 let fullName = computed(() => { console.log('計算屬性被呼叫了'); return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + ' _ ' + lastName.value; }) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
03、效果如下: