本文主要是介绍【vue】watch 侦听器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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
这篇关于【vue】watch 侦听器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!