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, watch } from './vue.esm-browser.js'createApp({setup() {const hobby = ref("")const date = reactive({year: "",month: ""})//监听hobby变化watch(hobby, (newVal, oldVal) => {console.log("oldVal :", oldVal, "newVal :", newVal)})//监听某个值,如date.yearwatch(() => date.year, (newVal, oldVal) => {console.log("oldVal :", oldVal, "newVal :", newVal)})//监听date变化//发现date变化时,新旧值一样//因为数组和对象通过引用传递,而不是创建一个新的对象或数组//newVal, oldVal是指向同一个对象,所以变化时,oldVal, newVal是一样的watch(date, (newVal, oldVal) => {console.log("oldVal :", oldVal, "newVal :", newVal)})return {date,hobby}}}).mount("#app")</script>
</body></html>
参考
https://www.bilibili.com/video/BV1nV411Q7RX