<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script type="text/javascript" src="../js/vue.js"></script> <title>监视属性深度监视</title> </head> <body> <div id="root"> <h1>今天天气{{inFo}}</h1> <!-- 绑定事件的时候,事件 @xxx="yyy",yyy可以写一些简单的语句 --> <!-- <button @click="isHot=!isHot">切换天气</button> --> <button @click="chang">切换天气</button> </div> <script> const vm = new Vue({ el: "#root", data: { isHot: true, }, methods: { chang() { this.isHot = !this.isHot; } }, computed: { inFo() { return this.isHot ? '炎热' : '凉爽'; } }, watch: { /* //正常写法 isHot: { // immediate:true,//初始化时让handler调用一下 //handler在isHot发生改变时触发 handler(newValue, oldValue) { console.log(newValue, oldValue) } }, /* //监视多级结构中某个属性的变化 */ /* //简写 isHot(newValue, oldValue){ console.log(newValue, oldValue) } */ } }) // 完整的写法 // vm.$watch("isHot",{ // // immediate:true,//初始化时让handler调用一下 // //handler在isHot发生改变时触发 // handler(newValue, oldValue) { // console.log(newValue, oldValue) // } // }) //简写 但是函数中不允许写成箭头函数 vm.$watch("isHot",function (newValue, oldValue) { console.log(newValue, oldValue) }) </script> </body> </html>