一、监听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><!-- <script src="vue.global.js"></script> -->
</head>
<body><div id="app">星期<select v-model="select"><option value="">请选择</option><option value="星期一">星期一</option><option value="星期二">星期二</option><option value="星期三">星期三</option></select><br>年<select v-model="web.year"><option value="">请选择</option><option value="2023">2023</option><option value="2024">2024</option><option value="2025">2025</option></select>月<select v-model="web.month"><option value="">请选择</option><option value="10">10</option><option value="11">11</option><option value="12">12</option></select></div><script type="module">import {createApp, ref, reactive, watch} from './vue.esm-browser.js'// const {createApp, reactive} = VuecreateApp({// setup选项,用于设置响应式数据和方法等setup(){ const select = ref("")const web = reactive({year:"2023",month:"10"})watch(select,(newValue,oldValue)=>{console.log("newValue",newValue,"oldValue",oldValue)if(newValue == "星期二"){console.log("今天是星期二")}})// 监听webwatch(web,(newValue,oldValue)=>{ console.log("newValue",newValue,"oldValue",oldValue)})// 监听web中某个属性watch(()=>web.year,(newValue,oldValue)=>{ console.log("newValue",newValue,"oldValue",oldValue)if(web.year == "2023"){console.log("选择了2023年")}}) return{web,select }}}).mount("#app")// mount为挂载</script>
</body>
</html>
JS中对象和数组是通过引用传递的,而不是通过值传递,当修改对象或数组的值时,实际上修改的是对象或数组的引用,而不是创建一个新的对象或数组,所以,若修改了对象或数组的值,则打印出来的结果是修改后的值。
二、自动监听watchEffect
伪代码:
</script><script type="module">import {createApp, ref, reactive, watchEffect} from './vue.esm-browser.js'// const {createApp, reactive} = VuecreateApp({// setup选项,用于设置响应式数据和方法等setup(){ const select = ref("")const web = reactive({year:"2023",month:"10"})watchEffect(()=>{console.log("---------自动监听----")if(select.value == "星期三"){console.log("选择了星期三")}if(web.year == "2025"){console.log("选择了2025年")}if(web.month == "12"){console.log("选择了12月")}console.log("-----------监听结束--------------")})return{web,select }}}).mount("#app")// mount为挂载
</script>