| 12345678910111213141516171819202122232425262728293031323334353637 |
- <template>
- <div>
- <h3>watch与watchEffect</h3>
- <p>今天是{{weather}},气温是{{temp}}</p>
- <button @click="changeWeather">修改天气</button>
- <button @click="changeTemp">修改气温</button>
- </div>
- </template>
- <script setup>
- import { ref, watch, watchEffect } from "vue";
- let weather = ref("晴天");
- let temp = ref(24);
- function changeWeather() {
- weather.value = '雨天';
- }
- function changeTemp() {
- temp.value -= 1;
- }
- // watch([weather,temp],(value)=>{
- // console.log(value)
- // let [newWeather,newTemp] = value;
- // if(newWeather === '雨天' && newTemp <= 10) {
- // temp.value = 10;
- // alert("当前温度过低")
- // }
- // })
- // 立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行。
- watchEffect(()=>{
- if(weather.value === '雨天' && temp.value <= 10) {
- temp.value = 10;
- alert("当前温度过低")
- }
- })
- </script>
- <style lang="scss" scoped></style>
|