例7:货币换算 【 侦听属性的函数在页面加载时立即执行 immedirate:true 】

HTML

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue.js</title>
	<link rel="stylesheet" type="text/css" href="style/index.css" />
	<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
	
	<div id="box">
		<p>: <input type="number" v-model='CNY'></p>
		=
		<p>$: <input type="number" v-model='dollar'></p>

	</div>

	<script src="js/index.js"></script>
</body>
</html>

JS

// var vm=new Vue({
// 	el:'#box',
// 	data:{
// 		CNY:1,
// 		dollar:1,
// 		rate:7.0119
// 	},
// 	watch:{
// 		CNY:function(newValue){
// 			this.dollar=newValue/this.rate;
// 		},
// 		dollar:{
// 			handler:function(newValue){
// 				this.CNY=newValue*this.rate;
// 			},
// 			immediate:true
// 		}
// 	}
// })

var vm=new Vue({   /*书写格式二*/
	el:'#box',
	data:{
		CNY:1,
		dollar:1,
		rate:7.0119
	}
})

vm.$watch('CNY',function(newValue){
	this.dollar=newValue/this.rate;
})

vm.$watch('dollar',function(newValue){
	this.CNY=newValue*this.rate;
},{
	immediate:true
})

你可能感兴趣的:(货币换算,侦听属性)