一、计算属性的基本使用
computed:{
FullName:function () {
return this.firstName+' '+ this.lastName
}
}
二、计算属性的复杂操作
1、提取data中books中的值的方法
data: {
books:[
{id:110,name:'unix编程艺术',price:119},
{id:111,name:'现代操作系统',price:105},
{id:112,name:'深入理解计算机原理',price:98},
{id:113,name:'代码大全',price:112}
]
},
- 方法一:
let total = 0;
for(let i = 0;i<this.books.length;i++){
total +=this.books[i].price
}
- 方法二:
let total = 0;
for(let i in books){
total +=this.books[i].price
}
- 方法三:
let total = 0;
for(let i of books){
total += this.books.price
}
- 方法四 reduce:
this.books.reduce(function(preValue,n){
return preValue+n},0)
三、计算属性和methods的对比
1、通过定义methods会执行多次
2、通过定义计算属性只执行一次,性能更好
3、例子
<body>
<div id="app">
<!--<h1>{{firstName+lastName}}</h1>-->
<!--computed-->
<h1>{{fullName}}</h1>
<h1>{{fullName}}</h1>
<h1>{{fullName}}</h1>
<h1>{{fullName}}</h1>
<!--methods-->
<h1>{{fullName1()}}</h1>
<h1>{{fullName1()}}</h1>
<h1>{{fullName1()}}</h1>
<h1>{{fullName1()}}</h1>
</div>
<script src = "../js/vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data: {
firstName:'Xiong',
lastName:'Er'
},
methods:{
fullName1(){
console.log("执行methods")
return this.firstName+' '+this.lastName
}
},
computed:{
fullName:function () {
console.log("执行computed")
return this.firstName+' '+this.lastName
}
}
})
</script>
</body>
运行结果
可见methods执行了四次,而computed执行一次,性能好