提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

  1. <template>
  2. <div class="person">
  3. <h1>需求水温达到50或水位达到20cm则联系服务器</h1>
  4. <h2 id="demo">水温{{temp}}</h2>
  5. <h2>水位{{height}}</h2>
  6. <button @click="changePrice">水温+1</button>
  7. <button @click="changeSum">水位+10</button>
  8. </div>
  9. </template>
  10. <script lang="ts" setup name="Person">
  11. import {ref,watch,watchEffect} from 'vue'
  12. // 数据
  13. let temp = ref(0)
  14. let height = ref(0)
  15. // 方法
  16. function changePrice(){
  17. temp.value += 10
  18. }
  19. function changeSum(){
  20. height.value += 1
  21. }
  22. // 用watch实现,需要明确的指出要监视:temp、height
  23. watch([temp,height],(value)=>{
  24. // 从value中获取最新的temp值、height值
  25. const [newTemp,newHeight] = value
  26. // 室温达到50℃,或水位达到20cm,立刻联系服务器
  27. if(newTemp >= 50 || newHeight >= 20){
  28. console.log('联系服务器')
  29. }
  30. })
  31. // 用watchEffect实现,不用
  32. const stopWtach = watchEffect(()=>{
  33. // 室温达到50℃,或水位达到20cm,立刻联系服务器
  34. if(temp.value >= 50 || height.value >= 20){
  35. console.log(document.getElementById('demo')?.innerText)
  36. console.log('联系服务器')
  37. }
  38. // 水温达到100,或水位达到50,取消监视
  39. if(temp.value === 100 || height.value === 50){
  40. console.log('清理了')
  41. stopWtach()
  42. }
  43. })
  44. </script>