[Vue]侦听属性watch(十)
作者:互联网
watch
- 用于侦听变量的变化,然后进行相应的处理
- 尽量不使用watch使用computed代替
示例源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>hellovue</title>
</head>
<body>
<div id="myApp">
今天是3月3日发卖的任天堂新一代主机Switch的价格是:{{price}}日元,含税价格为:{{priceInTax}} 日元,折合人民币为:{{priceChinaRMB}}元。
<button @click="btnClick(10000)">加价10000日元</button>
</div>
<script>
var myApp = new Vue({
/*绑定标签的id*/
el: '#myApp',
/*标签上绑定初始的数据*/
data: {
price: 29980,
priceInTax: 0,
priceChinaRMB: 0,
},
watch: {
price: function (newVal, oldVal) {
console.log(newVal, oldVal)
this.priceInTax = Math.round(this.price * 1.08);
this.priceChinaRMB = Math.round(this.priceInTax / 16.75);
},
},
methods: {
btnClick: function (newPrice) {
this.price += newPrice;
},
},
});
</script>
</body>
</html>
END
标签:Vue,price,watch,oldVal,priceChinaRMB,priceInTax,侦听,Math 来源: https://www.cnblogs.com/leoshi/p/12427909.html