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、效果如下:
标签:10,vue,temp,Vue3,watchEffect,TypeScript,10px,ref From: https://www.cnblogs.com/tianpan2019/p/18365493