1. 程式人生 > >Vue 的觀察屬性($watch)

Vue 的觀察屬性($watch)

與computer屬性類似,用於觀察量的變化,然後進行相應的處理。(從Angular而來)

 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<title>Document</title>

</head>

<body>

<div id = "myApp">

<p>任天堂釋出的新主機價格是:{{price}}元,含稅價格為{{priceInTax}}元,摺合人名幣為:{{priceChinaRMB}}元</p>

<button @click = "btnClick(10000)" >加價10000</button>

</div>

 

<script>

var myApp = new Vue({

el:"#myApp",

data:{

price:0,

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;

},

},

});

myApp.price = 29980;

</script>

</body>

</html>