data中的数据,可以通过插值语法直接显示到页面上,但有时需要先处理一下(比如把多个数据合并),再显示到页面。
此时就会用到计算属性(vue实例的computed属性)。
用法
HTML:在模板里面指定属性名
<h2>{{fullName}}</h2>
JS:在computed属性里面,添加方法。
const app = new Vue({
el: '#app',
data: {
firstName: 'Lebron',
lastName: 'James'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
案例
显示图书总价
<div id="app">
<h2>总价格: {{totalPrice}}</h2>
<!--totalPrice不需要加小括号-->
</div>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 110, name: 'Unix编程艺术', price: 119},
{id: 111, name: '代码大全', price: 105},
{id: 112, name: '深入理解计算机原理', price: 98},
{id: 113, name: '现代操作系统', price: 87},
]
},
computed: {
totalPrice: function () {
let result = 0
for (let i=0; i < this.books.length; i++) {
result += this.books[i].price
}
return result
//可以直接在for里面return this.books.reduce()
//常用的几个高阶函数有 filter/map/reduce
}
}
//这里的for循环可以使用:
// for (let i in this.books) {
// this.books[i]
// }
//或
// for (let book of this.books) {
//
// }
})
</script>
setter和getter
get方法
为什么计算属性写成函数,使用的时候却当一个普通属性来使用,不用加小括号呢?
因为我们平时使用的,是computed的简写形式,比如上面【用法】这个案例,如果完整写的话,fullName属性的值不是函数,而是对象,对象里面包含set方法和get方法,如下所示:
computed: {
fullName: {
set: function () {
},
get: function () {
return this.firstName + ' ' + this.lastName
}
}
}
使用计算属性,其实是调用get方法,来输出return
的内容。
计算属性通常是只读属性,因为计算属性通常只实现get方法,不需要实现set方法。所以set方法一般会删除掉:
computed: {
fullName: {
get: function () {
return this.firstName + ' ' + this.lastName
}
}
}
既然只实现get方法,每次都写get挺麻烦的,所以我们通常会简写成下面的形式:
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
这个function,对应的就是get方法。所以fullName不需要加小括号,因为他是属性,不是方法。之所以看着像方法,只是因为简写了。
set方法(了解,通常不需要实现set方法)
要实现set方法,需要给set方法传递一个参数:
set:function(newValue){
console.log(newValue)
}
我们打开浏览器的调试窗口,输入app.fullName='yao kai'
,则值yao kai
会被传递给newValue,console的结果是yao kai
。
拿到newValue之后,我们想把它保存给data,该如何操作呢:
set: function(newValue) {
console.log(newValue);
const names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[1];
}
计算属性和methods的对比
计算属性有缓存,methods没有缓存。
如果变量没有变化,那么计算属性就直接把上次的结果返回,而不会重新计算,这样就提升了性能。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。