计算属性computed
在模板中放入太多的逻辑会让模板过重且难以维护
计算属性 使html代码更简洁
<div id = "app">
<h2>{{firstName + ' ' + lastName}}</h2>
<h2>{{fullName}}</h2>
</div>
<script src = './vue.js'></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'fx',
lastName: 'zheng'
},
computed: {
fullName: function(){
return this.firstName + ' ' + this.lastName;
}
}
})
</script>
<h2>总额:{{totalPrice}}</h2>
<script>
data: {
books: [
{id: 01, bName: '计算机原理', price: 90},
{id: 02, bName: '代码大全', price: 109},
{id: 03, bName: 'hha', price: 40}
]
},
computed: {
totalPrice: function(){
let result = 0;
for (const book of this.books) {
result += book.price;
}
return result;
}
}
</script>
计算属性的setter 和 getter
computed: {
fullName: function(){
return this.firstName + ' ' + this.lastName;
}
}
真实写法:
computed: {
fullName:{
setter(){},
getter: function(){
return this.firstName + ' ' + this.lastName;
}
}
}
一般不写setter函数,所以简写为第一种写法。此时 fullName属性为只读属性。
调用fullName属性时,自动执行getter函数 。
若要使用setter,一般要传参, 接受输入的值
setter(newValue){
const name = newValue.split(' ');
this.firstName = name[0];
this.lastName = name[1];
}
计算属性的缓存
计算属性内部有缓存,methods没有,所以计算属性性能更高,推荐使用
<div id = "app">
computed:
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
methods:
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
</div>
methods: {
getFullName: function(){
console.log('methods');
return this.fN + ' ' + this.lN;
}
},
computed: {
fullName: function(){
console.log('computed');
return this.fN + ' ' + this.lN;
}
}
计算属性,只要涉及的值没有改变,则只计算一次,methods则每次调用都要重新计算一次