watchEffect:自动监听值的变化
- 获取旧值时,不是很方便,建议用watch
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><div id="app">爱好<select v-model="hobby"><option value="">请选择</option><option value="reading">阅读</option><option value="swimming">游泳</option><option value="running">跑步</option></select><hr>年<select v-model="date.year"><option value="">请选择</option><option value="2021">2021</option><option value="2022">2022</option><option value="2023">2023</option><option value="2024">2024</option></select>月<select v-model="date.month"><option value="">请选择</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option></select></div><script type="module">import { createApp, reactive, ref, watchEffect } from './vue.esm-browser.js'createApp({setup() {const hobby = ref("")const date = reactive({year: "",month: ""})//自动监听watchEffect(() => {console.log("----- 自动监听开始")console.log(hobby.value)console.log(date.year, date.month)console.log("自动监听结束 -----")})return {date,hobby}}}).mount("#app")</script>
</body></html>
参考
https://www.bilibili.com/video/BV1nV411Q7RX