一、为什么使用Vue的计算属性? 在Vue应用中,在模板中双向绑定一些数据或者表达式({{***}}),但是表达式如果过长,或者逻辑更为复杂时,就会变得臃肿甚至难以维护和阅读,而使用methods较为耗费性能,多次重复使用,多次重复调用,比如这样的写法:
<div class="app">
<table border="1">
<thead>
<th>学科</th>
<th>分数</th>
</thead>
<tbody>
<tr>
<td>数学</td>
<td><input type="text" v-model="Math"></td>
</tr>
<tr>
<td>英语</td>
<td><input type="text" v-model="English"></td>
</tr>
<tr>
<td>化学</td>
<td><input type="text" v-model="chemistry"></td>
</tr>
<tr>
<!------------------------过长的表达式显得十分臃肿,代码的可读性不好---------.-->
<td>总分</td>
<td>{{Math + English + chemistry}}</td>
</tr>
<tr>
<td>平均分</td>
<td>{{(Math + English + chemistry)/3}}</td>
</tr>
</tbody>
</table>
在这种情况下,vue给我们提供了一个特别好的解决方案:计算属性:我们可以把这些计算的过程写到一个计算属性中去,然后让它动态的计算就可以了。计算属性是vue实例中的选项:computed通常里面每一个都是计算相关函数,返回最后计算出来的值。
<p>{{getData()}}</p>
<!-- 使用Vue计算属性 -->
<p>{{fullName}}</p>
//-----------------------------------------------
var vm = new Vue({
el: '#app',
data: {
msg:"中国-",
msg2:"山东。"
},
methods: {
//利用methods方法返回想要的格式数据
getData(){
return this.msg+this.msg2
}
},
computed: {
fullName:function(){
return this.msg+this.msg2
}
},
});
arr:[{
name:“zs”,
age:15
},{
name:“ls”,
age:20
}]
<!-- 运算 -->
<p>{{arr[0].age+arr[1].age}}</p>
<!--使用Vue计算属性-->
<p>{{sumAge}}</p>
computed: {
fullName:function(){
return this.msg+this.msg2
},
sumAge:function(){
let sum=0;
// for (const item of this.arr) { //ES6>当前item就是循环的当前对象---OK
// sum=item.age+sum
// }
// this.arr.forEach(item => {//使用数组的forEach循环
// sum=item.age+sum
// });
// this.arr.some((item,i)=>{
// sum=item.age+sum
// })
// for(let i=0;i<this.arr.length;i++){
// sum=this.arr[i].age+sum
// }
for(let i in this.arr){
sum=this.arr[i].age+sum
}
return sum;//通过简单处理返回最终的属性值。
}
},
其实computed就是一个属性:
fuu:{
set:function(Newvalue){
console.log('你改动了计算属性值!')
//Newvalue 你可以对它解析,重新赋值data值(因为改动的不是计算属性而是data值)msg+msg2
},
//一般不需要set函数,只需要get函数处理返回结果
get:function(){
return 'OKK,你拿到了!' //计算属性的值
}
}
总结:计算属性和methods的区别:
计算属性一般就是用来通过其他的数据计算出一个新数据,而且它有一个好处就是它把新的数据缓存下来了,如果data中相关的数据没有发生改变,那么再次调用它的时候会返回它的缓存的数据,这就极大的提高了我们程序的性能;如果写在methods里,每次调用都会重新计算,都是一次新的调用,不会缓存,所以用计算属性比较好,因为有缓存。