这是我参与「第四届青训营 」笔记创作活动的的第18天
什么是计算属性
我们知道,在模板中可以直接通过插值语法显示一些data中的数据。
但是在某些情况,我们可能需要对数据进行一些转化后再显示,或者需要将多个数据结合起来进行显示 比如我们有firstName和lastName两个变量,我们需要显示完整的名称。 但是如果多个地方都需要显示完整的名称,我们就需要写多个{{firstNamel}} {{lastName}}
我们可以将上面的代码换成计算属性: 计算属性是写在实例的computed选项中的。
computed计算得到的属性可以缓存,下次直接调用,而methods每次调用都要计算 原因∶计算属性会进行缓存,如果数据没有更改,多次使用时,计算属性只会调用一次,而不是重新计算
<div id="a">
<!-- 直接拼接 过于繁琐 -->
<h3>{{first + ' ' + last}}</h3>
<h3>{{first}} {{last}}</h3>
<!-- 通过定义methods -->
<h3>{{getfullname()}}</h3>
<h3>{{getfullname()}}</h3>
<!-- 通过computed -->
<h3>{{fullname}}</h3>
<h3>{{fullname}}</h3>
<h3>总价格:{{totalprice}}</h3>
</div>
<script src="./vue.js"></script>
<script>
const a = new Vue({
el: '#a',
data: {
message: '你好',
first: 'heart',
last: 'stopper',
books: [
{ id: 001, name: 'aaa', price: 100 },
{ id: 002, name: 'bbb', price: 90 },
{ id: 003, name: 'ccc', price: 110 },
{ id: 004, name: 'ddd', price: 88 },
// { id : '001', song : 'Say So', singer : 'Doja Cat'},
// { id : '002', song : 'for him', singer : 'Troye Sivan'},
// { id : '003', song : "we don't talk anymore", singer : 'Charlie Puth'},
// { id : '004', song : 'Oops', singer : 'Charlie Puth'},
]
},
methods: {
getfullname: function () {
console.log("getfullname");
return this.first + ' ' + this.last
},
},
// 计算属性,当作属性来用
computed: {
fullname: function () {
console.log('fullname');
return this.first + ' ' + this.last
},
totalprice: function () {
let result = 0;
// for(let i = 0; i < this.books.length; i++)
// {
// result += this.books[i].price;
// }
// for( let i in this.books){
// result += this.books[i].price;
// }
for (let book of this.books) {
result += book.price
}
// for in用来遍历可枚举属性,for of用来遍历可送代对象要送。对于数组,前者是遍历索引,后者是遍历值
return result;
}
}
})
</script>
计算属性的setter和getter
每个计算属性都包含一个getter和一个setter
在上面的例子中,我们只是使用getter来读取。 在某些情况下,你也可以提供一个setter方法(不常用) 在需要写setter的时候,代码如下∶
<div id='app'>
<h3>{{fullname}}</h3>
</div>
<script src='./vue.js'></script>
<script>
const app = new Vue({
el: '#app',
data: {
first: 'heart',
last: 'stopper',
},
computed: {
// 完整的计算属性属性对应一个对象,里面有一个set方法一个get方法
// 一般不希望有set属性 只读属性
fullname: {
set: function (newvalue) {
// console.log('------',newvalue);
const names = newvalue.split(' ');
this.first = names[0];
this.last = names[1];
},
get: function () {
// return this.first + ' ' + this.last;
return 'abc'
}
}
}
})
</script>