<!DOCTYPE html>
<html lang="zh">
<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>vue.js自学:如何使用属性计算(复杂使用方法)</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>商品的总价格为:{{totalPrice}}</h1>
</div>
</body>
<script type="text/javascript">
let app = new Vue({
el:’#app’,
data:{
books:
[
{id:’0’,name:’小叮当’,price:30},
{id:’0’,name:’小叮当’,price:30},
{id:’0’,name:’小叮当’,price:30},
]
},
computed:{
totalPrice:function(){
let result = 0
//computed的好处,是computed有缓存作用
for(let i = 0;i<this.books.length;i++){
result += this.books[i].price
}
//ES6新增语法 (let i in this.xx)
for(let i in this.books){
result += this.books[i].price
}
//ES6新增语法 book 被解析出整个对象
for(let book of this.books){
result += book.price
}
return result
}
}
})
</script>
</html>