1、监视多级结构中某个属性的变化
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>watch深度监视</title><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root"><hr><h3>a的值是:{{numbers.a}}</h3><button @click="numbers.a++">点我让a+</button>
</div>
<script type="text/javascript">Vue.config.productionTip=false;const vm = new Vue({el:"#root",data:{numbers:{a:1,b:2,}},watch:{//监视多级结构中某个属性的变化'number.a':{handler(newvalue, oldvalue) {console.log(newvalue,oldvalue);}}}});
</script>
</body>
</html>
2、监视多级结构中所有属性的变化。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>watch深度监视</title><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root"><hr><h3>a的值是:{{numbers.a}}</h3><button @click="numbers.a++">点我让a+</button><hr><h3>b的值是:{{numbers.b}}</h3><button @click="numbers.b++">点我让b+</button></div>
<script type="text/javascript">Vue.config.productionTip=false;const vm = new Vue({el:"#root",data:{numbers:{a:1,b:2,}},watch:{//监视多级结构中某个属性的变化'number.a':{handler(newvalue, oldvalue) {console.log(newvalue,oldvalue);}},//监视多级结构中所有属性的变化。numbers: {deep:true,handler(newvalue, oldvalue) {console.log(newvalue,oldvalue)}}}});
</script>
</body>
</html>
3、监视简写 当只有handler 时简写如下:
4、监视属性姓名案例
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>监视属性姓名案例</title><!--引入vue--><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root">姓:<input type="text" v-model="firstname"><br>名:<input type="text" v-model="lastname"><br>姓名:<span>{{fullname}}</span><br>
</div>
<script type="text/javascript">Vue.config.productionTip=false;new Vue({el:"#root",data:{firstname:'张',lastname:'三',fullname:'张-三',},watch:{firstname: {handler(newvalue,oldvalue){//延迟一秒执行setTimeout(()=>{this.fullname=newvalue+'-'+this.lastname;},1000);}},lastname: {handler(newvalue, oldvalue) {setTimeout(()=>{this.fullname=this.firstname+'-'+newvalue;},1000)}}}})
</script>
</body>
</html>
5、计算属性与监视属性的区别