计算属性
设计的初衷在千减轻模板上的业务负担, 当数据链上出现复杂衍生数据时,我们更期望以一种易维护的方式去使用它。
- 基本使用
<div id="app">
<h2>{{firstName+lastName}}</h2>
<h2>{{firstName}}{{lastName}}</h2>
<h2>{{getFullName()}}</h2><!--方法-->
<h2>{{fullName}}</h2><!--<属性-->
</div>
<script src="../Js/vue.js"></script>
<script>
let app = new Vue({
el: '#app',
data: {
firstName: '夏吕',
lastName: '千千',
},
/* computed:计算属性*/
computed: {
fullName: function () {
return this.firstName + this.lastName
}
},
methods: {
getFullName() {
return this.firstName + this.lastName
}
}
})
</script>
- 复杂操作
<div id="app">
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src="../Js/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
/*数组里的 是对象*/
book: [
{id: 101, name: '代码大全', price: 102},
{id: 102, name: '编程艺术', price: 89},
{id: 103, name: '深入理解计算机原理', price: 82},
{id: 104, name: '现代操作系统', price: 88},
]
},
computed: {
totalPrice: function () {
let result = 0
for
(let
i = 0;
i < this.book.length;
i++
)
{
result += this.book[i].price
}
return result
}
}
})
</script>
- 计算属性setter和getter(计算属性的本质)
<div id="app">
{{fullName}}
</div>
<script src="../Js/vue.js"></script>
<script>
var app=new Vue({
el:'#app',
data:{
firstName:'任',
lastName:'阳峰'
},
computed: {
fullName:
{
set:function(newValue)
{
const names=newValue.split(' ');
this.firstName=names[0];
this.lastName=name[1];
},
get:function () {
return this.firstName+' '+this.lastName
}
}
}
})
</script>
- 计算属性性能比methods高
计算属性会进行缓存,如果多次使用时,只会调用一次。
<div id="app">
<!--函数调用四次-->
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<!--只调用一次-->
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
</div>
<script src="../Js/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
firstName: '任',
lastName: '阳峰'
},
computed: {
fullName: function () {
console.log("hahahaha");
return this.firstName + this.lastName
}
},
methods:
{
getFullName:function () {
console.log("hahahaha");
return this.firstName+this.lastName;
}
}
})
</script>