watchEffect监听

watchEffect

​ 官网:立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行该函数。

watch对比watchEffect:

​ 都能监听响应式数据的变化,不同的是监听数据变化的方式不同

watch:要明确指出监视的数据

watchEffect:不用明确指出监视的数据(函数中用到哪些属性,那就监视哪些属性)。

<template>
  <div class="person">
    <h2>需求: 当水温达到60° 或者 水位达到80cm时, 给服务器发请求</h2>
    <h2>当前水温:{{temp}}°C</h2>
    <h2>当前水位:{{height}}cm</h2>
    <button @click="changeTemp">点我水温+10</button>
    <button @click="changeHeight">点我高度+10</button>
  </div>
</template>

<script setup lang="ts" name="Person">
  import {ref, watch, watchEffect} from 'vue'

  //数据
  let temp = ref(10);
  let height = ref(0);

  //函数
  function changeTemp() {
    temp.value += 10;
  }
  
  function changeHeight() {
    height.value += 10;
  }

  //监听 -- watch 版本
  // watch([() => temp.value, () => height.value], (newValue, oldValue) => {
  //   let [newTemp, newHeight] = newValue;
  //   if(newTemp >= 60 || newHeight >= 80) {
  //     console.log('给服务器发送请求提示'); 
  //   }
  //   console.log(newValue, '-', oldValue)
  // })

  //监听 -- watchEffect 版本 可以看到不用明确指出监视对象了
  watchEffect(() => {
    // console.log('@')
    if(temp.value >= 60 || height.value >= 80) {
      console.log('给服务器发送请求提示'); 
    }
  })
</script>

<style>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px; /* 盒子阴影 */
  border-radius: 10px;
  padding: 20px;
}

button {
  margin: 0 5px;
}
</style>
posted @ 2024-12-24 09:44  如此而已~~~  阅读(37)  评论(0)    收藏  举报
//雪花飘落效果