<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>VUE监听属性</title>
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="app">
<p style="font-size: 25px;">自增器</p>
<button @click="counter++" style="font-size: 25px;">点我</button>
</div>
<script>
var vm=new Vue({
el:'#app',
data:{
counter:1
}
})
vm.$watch('counter',function(nval,oval){
console.log('自增器值的变化:'+oval+'变为:'+nval+'|')
})
</script>
</body>
</html>
则每次单击按钮的时候,console的输出值会自增。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>VUE监听案例2</title>
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="computed_props">
千米:<input type="text" v-model="kilometers" />
米:<input type="text" v-model="meters" />
</div>
<script>
var vm=new Vue({
el:'#computed_props',
data:{
kilometers:0,
meters:0
},
methods:{},
watch:{
kilometers:function(val){
this.kilometers=val;
this.meters=val*1000;
},
meters:function(val){
this.kilometers=val/1000;
this.meters=val;
}
}
})
//$watch是一个实例方法;
vm.$watch('kilometers',function(newValue,oldValue){
document.getElementById('info').innerHTML='修改前值为:'+oldvalue+",修改后值为:"+newvalue;
})
</script>
</body>
</html>