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>水溫到30,水位到40,報警</h2> <h2>當前水溫:{{ temp }}</h2> <h2>當前水位:{{ height }}</h2> <button @click="changeTemp">水溫+10</button> <button @click="changeHeight">水位+10</button> </div> </template> <script lang="ts" name="Person001" setup> import {ref, watchEffect} from 'vue' let temp = ref(0) let height = ref(0) function changeTemp() { temp.value += 10 } function changeHeight() { height.value += 10 } // 自動監視,減少程式碼量 watchEffect( () => { if (temp.value >= 30) { console.log('水溫超過30') } if (height.value >= 40) { console.log('水位超過40') } } ) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
3、效果如下: