watch与watchEffect监听使用

151 阅读1分钟

watch与watchEffect监听使用

<script setup>
import {reactive, ref, watch, watchEffect} from "vue";

const date = reactive({
  year:'',
  month:''
});

//监听整个日期
watch(date,(newValue,oldValue)=>{
  console.log("newValue:",newValue.year)
})

//监听data中的某个属性
watch(()=>date.year,(newValue,oldValue)=>{
  console.log("year-newValue:",newValue)
})

//自动监听,一般很少用
watchEffect(()=>{
  console.log("自动监听开始");
  if (date.year ==="2025"){
    console.log("2025年");
  }
  if (date.year ==="2024"){
    console.log("2024年")
  }
  if (date.month ==="11"){
    console.log("11月份")
  }
  })

</script>

<template>
  <div>
  <label for="year">年:</label>
  <select v-model="date.year" id="year">
    <option value="">请选择</option>
    <option value="2025">2025</option>
    <option value="2024">2024</option>
    <option value="2023">2023</option>
    <option value="2015">2015</option>
  </select>

  <label for="month">月:</label>
  <select v-model="date.month" id="month">
    <option value="">请选择</option>
    <option value="12">12</option>
    <option value="11">11</option>
    <option value="10">10</option>
  </select>
  </div>
</template>