目录
1、computed基本使用
<div id="demo">
<!--其他方法 -->
<h2>{{ firstName + ' ' + lastName }}</h2>
<h2>{{ firstName }} {{ lastName }}</h2>
<h2>{{ getName() }}</h2>
<!--使用计算属性 -->
<h2>{{ fullName }}</h2>
</div>
<script>
let vm = new Vue({
el: '#demo',
data: {
firstName: 'LeBron',
lastName: 'James',
},
//计算属性
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName;
}
},
methods: {
getName: function () {
return this.firstName + ' ' + this.lastName;
}
}
});
</script>
2、案例
<div id="demo">
<table>
<tr>
<th>id</th>
<th>书名</th>
<th>价格</th>
</tr>
<tr v-for="item in books">
<th>{{item.id}}</th>
<th>{{item.name}}</th>
<th>{{item.price}}</th>
</tr>
</table>
<h2>总价格:{{allPrice}}</h2>
</div>
<script>
let vm = new Vue({
el: '#demo',
data: {
books: [
{id: 1, name: "悲惨世界", price: 100},
{id: 2, name: "代码大全", price: 200},
{id: 3, name: "深入理解计算机系统", price: 300},
{id: 4, name: "Unix编程艺术", price: 400},
{id: 5, name: "现代操作系统", price: 500}
],
},
computed: {
allPrice: function () {
let price = 0;
for (let i = 0; i < this.books.length; i++) {
price += this.books[i].price;
}
return price;
}
}
});
</script>
3、计算属性和methods的对比
两个computed和methods方法同时调用4次,对比
<div id="demo">
<!-- 直接拼接:过于繁琐 -->
<!-- <h2>{{message+' '+messages2}}</h2>-->
<!-- methods -->
<h2>{{ getFinal() }}</h2>
<h2>{{ getFinal() }}</h2>
<h2>{{ getFinal() }}</h2>
<h2>{{ getFinal() }}</h2>
<!-- 计算属性 -->
<h2>{{ final }}</h2>
<h2>{{ final }}</h2>
<h2>{{ final }}</h2>
<h2>{{ final }}</h2>
</div>
<script>
let vm = new Vue({
el: '#demo',
data: {
message: '对比',
messages2: '2',
},
computed: {
final: function () {
console.log('computed:final');
return this.message + ' ' + this.messages2;
}
},
methods: {
getFinal: function () {
console.log('methods:getFinal');
return this.message + ' ' + this.messages2;
}
}
});
</script>
可以看到,methods调用4次,computed只调用了一次。(函数调用和数据预处理缓存的区别)