您的位置:首页 > Web前端 > Vue.js

VUE之监听属性 watch

2021-01-10 22:14 603 查看
<!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>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: