data中数据有一个数组数据,数组中是一个个对象,比如一本书,有id,有价格,那么我们要通过计算属性计算出来所有的书本的总价格,展示出来。
源代码<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
[v-cloak]{
display: none;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<h2>姓名:{{fullName}}</h2>
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app=new Vue({
el:"#app",
data:{
firstName:"张",
lastName:'三',
books:[
{id:1,price:10},
{id:1,price:10},
{id:1,price:10}
]
},
computed:{
fullName:function(){
return this.firstName+" "+this.lastName;
},
totalPrice:function () {
let result=0;
for (const book of this.books) {
result+=book.price;
}
return result;
}
}
});
</script>
</body>
</html>
效果