Demo12.vue 851 B

123456789101112131415161718192021222324252627282930313233343536
  1. <template>
  2. <div>
  3. <h1>watch与watchEffect</h1>
  4. <h3>今天还{{ weather }},温度是{{ temp }}</h3>
  5. <button @click="changeWeather">修改天气</button>
  6. <button @click="changeTemp">修改温度</button>
  7. </div>
  8. </template>
  9. <script lang="ts" setup>
  10. import {ref,watch, watchEffect} from "vue"
  11. let weather = ref("雪天");
  12. let temp = ref(-10);
  13. function changeWeather() {
  14. weather.value = '晴天';
  15. }
  16. function changeTemp() {
  17. temp.value = 20;
  18. }
  19. // watch([weather,temp],(value) => {
  20. // console.log(value)
  21. // },{
  22. // deep: true,
  23. // immediate: true
  24. // })
  25. // 立即执行函数 同时 响应式地追踪其依赖 依赖改变自动更新
  26. watchEffect(()=>{
  27. console.log(weather.value,temp.value,'watchEffect')
  28. if(temp.value > 0) {
  29. alert("天气晴朗")
  30. }
  31. })
  32. </script>
  33. <style lang="scss" scoped>
  34. </style>