当页面中需要多次计算,可以使用计算属性,计算属性只会计算一次,并将计算结果缓存
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<p>单价:{{price}}</p>
<p>数量:{{num}}</p>
<p>总价:{{price * num}}</p>
<hr>
<p>总价:{{getTotalPrice()}}</p>
<p>总价:{{getTotalPrice()}}</p>
<p>总价:{{getTotalPrice()}}</p>
<hr>
<p>总价:{{totalPrice}}</p>
<p>总价:{{totalPrice}}</p>
<p>总价:{{totalPrice}}</p>
<hr>
<p>总价:{{totalPrice2}}</p>
<p>总价:{{totalPrice2}}</p>
<p>总价:{{totalPrice2}}</p>
</div>
</body>
</html>
<script src="js/vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
price: 10,
num: 8
},
methods: {
getTotalPrice() {
console.log("getTotalPrice");
var total = this.price * this.num;
return total;
}
},
computed: {
totalPrice() {
console.log("totalPrice");
var total = this.price * this.num;
return total;
},
totalPrice2() {
console.log("totalPrice2");
return this.getTotalPrice();
}
}
});
</script>