1.稍复杂操作案例
做字符串拼接时,可以使用插值操作显示出效果,但是在一些情况下,插值操作没有办法替代计算属性
<div id="app">
<h2>总价格:{{totalPrice}}</h2>
</div>
const app = new Vue({
el : '#app',
data : {
books : [
{id : 000, name : 'HTML', price : 56},
{id : 001, name : 'CSS', price : 68},
{id : 002, name : 'JS', price : 79},
]
},
computed : {
totalPrice : function () {
var result = 0;
for(var i = 0; i < this.books.length; i++) {
result += this.books[i].price;
}
return result;
}
}
})
image.png
2.geter和seter
每个计算属性都有一个getter和setter,完整的computed属性如下:
totalPrice和fullName计算属性都有get属性和set属性
computed : {
totalPrice : {
get : function() {
},
set : function() {
}
},
fullName : {
get : function() {
},
set : function() {
}
}
}
image.png
大多数的计算属性只使用到get方法,所以可以简化成第一种写法,也导致会将totalPrice误认成函数,toltalPrice只是一个计算属性,所以在插值操作时,不能写成toltalPrice()
1.使用get来获取数据
image.png
2.虽然set很少使用,但是也可以使用
image.png
image.png
网友评论