1.什么是计算属性,我们知道在前面学习vue入门程序的时候,一般都是通过mustache语法,从data里拿数据,然后显示,但有时候会出现,一些数据并不可以直接拿来用,而是要经过以一系列的操作后,才能使用,这时候,computed发挥了它的作用,其实method也可以实现,对某些数据进行处理再返回,那为什么要存在computed呢,那是因为computed提供了一个缓存机制,方法每调用一次都会执行一次,而计算属性,在第一次调用时,会执行一次,之后再调用时,不会再执行,数据已经被放到了缓存里面。
2.例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="content">
<h2>{{getName}}</h2>
<h2>{{getTotalPrice}}</h2>
</div>
<script src="./vue.js"></script>
<script>
const content = new Vue({
el: '#content',
data: {
firstName: 'chen',
lastName: 'shu',
cartoons: [
{id: 1,name: '海贼王',price: 100},
{id: 2,name: '火影忍者',price: 300},
{id: 3,name: '四驱兄弟',price: 1000},
{id: 4,name: '灵异的世界',price: 500},
{id: 5,name: '一人之下',price: 10000}
]
},
computed: {
getName() {
return this.firstName + this.lastName
},
getTotalPrice() {
//遍历数组的三种方式
let total = 0
for(let i of this.cartoons) {//拿到的是每一个元素
total += i.price
}
// let total = 0
// for(let i in this.cartoons) {//拿到的是每一个元素的索引
// total += this.cartoons[i].price
// }
// let total = 0
// for(let i = 0; i < this.cartoons.length; i++) {
// total += this.cartoons[i].price
// }
return total
}
}
})
</script>
</body>
</html>
3.结果