1.computed计算属性,它表示根据已有属性,计算得到一个新的属性
2.在computed里面写一个函数,这个函数很特殊,它的函数名,将来可以作为一个属性来使用
3.计算属性是依赖于缓存的,当页面中调用同一个计算属性多次的时候,后面的计算属性的值,会直接从第一次得到的结果中去取,所以说,它的性能比较高,推荐使用计算属性⭐
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./vue2.js"></script>
</head>
<body>
<div id="app">
<div>
<span>单价:{{price}} ----- 数量:{{count}}</span>
<button @click="count=count+1">增加</button>
<button @click="count=count-1">减少</button>
</div>
<p>总价:{{totalPrice}}</p>
<p>总价(加运费):{{totalPrice2}}</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
price: 100,
count: 2,
yunfei: 20
},
computed: {
totalPrice() {
return this.price * this.count
},
totalPrice2() {
// 注意,在computed中不能够使用异步函数
// setTimeout(() => {
// return this.price * this.count + this.yunfei
// }, 200);
return this.price * this.count + this.yunfei
}
}
})
</script>
</body>
</html>