Vue的计算属性

一、计算属性的基本使用

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}
      ]
    },

  1. 方法一:
let total = 0;
for(let i = 0;i<this.books.length;i++){
	total +=this.books[i].price
}
  1. 方法二:
let total = 0;
for(let i in books){
	total +=this.books[i].price
}
  1. 方法三:
let total = 0;
for(let i of books){
	total += this.books.price
}
  1. 方法四 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执行一次,性能好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值