Demo13.vue 990 B

12345678910111213141516171819202122232425262728293031323334353637
  1. <template>
  2. <div>
  3. <h3>watch与watchEffect</h3>
  4. <p>今天是{{weather}},气温是{{temp}}</p>
  5. <button @click="changeWeather">修改天气</button>
  6. <button @click="changeTemp">修改气温</button>
  7. </div>
  8. </template>
  9. <script setup>
  10. import { ref, watch, watchEffect } from "vue";
  11. let weather = ref("晴天");
  12. let temp = ref(24);
  13. function changeWeather() {
  14. weather.value = '雨天';
  15. }
  16. function changeTemp() {
  17. temp.value -= 1;
  18. }
  19. // watch([weather,temp],(value)=>{
  20. // console.log(value)
  21. // let [newWeather,newTemp] = value;
  22. // if(newWeather === '雨天' && newTemp <= 10) {
  23. // temp.value = 10;
  24. // alert("当前温度过低")
  25. // }
  26. // })
  27. // 立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行。
  28. watchEffect(()=>{
  29. if(weather.value === '雨天' && temp.value <= 10) {
  30. temp.value = 10;
  31. alert("当前温度过低")
  32. }
  33. })
  34. </script>
  35. <style lang="scss" scoped></style>