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"> <h1>情況一:監視【ref】定義的【基本型別】資料</h1> <h2>當前求和為:{{ sum }}</h2> <button @click="changeSum">點我sum+1</button> </div> </template> <script lang="ts" name="Person001" setup> import {ref, watch} from 'vue' let sum = ref(0) // 按鈕點選事件 function changeSum() { sum.value += 1; } // 監視sum和結束監視 const stopWatch = watch(sum, (newVal, oldVal) => { console.log('sum變化了,由', oldVal, '變為:', newVal); if (newVal >= 10) { stopWatch(); } }) </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
03、效果如下: