1.computed計算屬性,它表示根據已有屬性,計算得到一個新的屬性
2.在computed里面寫一個函數,這個函數很特殊,它的函數名,將來可以作為一個屬性來使用
3.計算屬性是依賴於緩存的,當頁面中調用同一個計算屬性多次的時候,后面的計算屬性的值,會直接從第一次得到的結果中去取,所以說,它的性能比較高,推薦使用計算屬性⭐
<!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">
<title>Document</title>
</head>
<body>
<div id="app">
<div>
<span>單價:{{price}}----------數量:{{count}}</span>
<button @click="count=count+1">增加</button>
<button @click="reduce()">減少</button>
</div>
<p>總價:{{totalPrice}}</p>
<p>總價(加運費):{{totalPrice2}}</p>
</div>
<script src="./lib/vue-2.4.0.js"></script>
<script>
let vm = new Vue({
el:'#app',
data:{
price:20,
count:0,
yunfei:10
},
computed: {
totalPrice(){
return this.price * this.count;
},
totalPrice2(){
// 注意,在computed中不能夠使用異步函數
// setTimeout(() => {
// return this.price * this.count + this.yunfei
// }, 200);
var totalprice = this.price * this.count + this.yunfei;
if (this.count === 0) {
totalprice = 0;
}
return totalprice;
}
},
methods: {
reduce(){
this.count = this.count - 1;
if (this.count<=0) {
this.count = 0;
}
}
}
})
</script>
</body>
</html>