计算属性体验(computed)
计算属性是一个属性,调用该属性不用加()
<body>
<div id="app">
<h2>{{firstName+' '+lastName}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName:'lebron',
lastName:'james',
},
//计算属性
computed: {
fullName:function () {
return this.firstName+' '+this.lastName;
}
},
methods: {
getFullName:function () {
return this.firstName+' '+this.lastName;
}
}
});
</script>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的复杂操作</title>
</head>
<body>
<div id="app">
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 110, name: 'js高级程序设计', price: 96},
{id: 111, name: '你所不知道的javascript', price: 50},
{id: 112, name: 'js数据结构', price: 32},
{id: 113, name: 'DOM编程艺术', price: 57},
],
},
computed: {
totalPrice: function () {
let result = 0;
for (let i = 0; i < this.books.length; i++) {
result += this.books[i].price;
}
return result;
}
}
});
</script>
</body>
</html>