Vue中的computed属性
理解:
1、computed用来监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义,然后就可以在页面上进行双向数据绑定展示出结果或者用作其他处理;
2、computed比较适合对多个变量或者对象进行处理后返回一个结果值,也就是数多个变量中的某一个值发生了变化则我们监控的这个值也就会发生变化,举例:购物车里面的商品列表和总金额之间的关系,只要商品列表里面的商品数量发生变化,或减少或增多或删除商品,总金额都应该发生变化。这里的这个总金额使用computed属性来进行计算是最好的选择
案例:
<template>
<div>
</div>
</template>
<script>
export default {
name: "demo",
data(){
return{
results:[
{name:'English',marks:70},
{name:'Math',marks:80},
{name:'History',marks:90}
]
}
},
created(){
console.log(this.totalMarks) //240
},
mounted(){},
methods:{},
computed:{
totalMarks(){
let total =0;
let that = this;
for(let i =0;i<that.results.length;i++){
total+=parseInt(that.results[i].marks)
}
return total
}
},
}
</script>
<style scoped>
</style>