计算属性的基本使用
使用mustache语法,进行简单的运算
使用方法
使用计算属性
以上三种都可以实现同样的效果
下面是代码实现过程:
<div id="app">
<h2>{{firstName + lastName}}</h2>
<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: 'Emi',
lastName: 'lia'
},
//计算属性
computed: {
fullName: function () {
return this.firstName + this.lastName
}
},
methods: {
getFullName() {
return this.firstName + this.lastName
}
}
})
</script>
计算属性的复杂使用
<div id="app">
<!--<h2>总价格:{{books[0}.price + ... + books[3}.price}</h2>-->
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 110, name: 'MYSQL从删库到跑路', price: 200 },
{id: 111, name: 'Java从跨平台到跨行业', price: 199 },
{id: 112, name: 'C语言从入门到入土', price: 201 }
]
},
computed: {
totalPrice: function () {
let result = 0;
for (let i = 0; i < this.books.length; i++){
result += this.books[i].price;
}
return result;
/*for (let i in this.books){
result += this.books[i].price;
}
for (let book of this.books){
result += book.price;
}*/
}
}
})
</script>