021、Vue3+TypeScript基础,使用watchEffect全自动监视修改的对象

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、效果如下:

 

posted @ 2024-08-18 12:35  像一棵海草海草海草  阅读(2)  评论(0编辑  收藏  举报