vue8---计算属性(computed)

计算属性computed

在模板中放入太多的逻辑会让模板过重且难以维护
计算属性 使html代码更简洁

<div id = "app">
    <h2>{{firstName + ' ' + lastName}}</h2>
    <h2>{{fullName}}</h2>
</div>
  <script src = './vue.js'></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        firstName: 'fx',
        lastName: 'zheng'
      },
      computed: {
        fullName: function(){
          return this.firstName + ' ' + this.lastName;
        }
      }
    })
  </script>
<h2>总额:{{totalPrice}}</h2>
<script>
data: {
	books: [
		{id: 01, bName: '计算机原理', price: 90}, 
		{id: 02, bName: '代码大全', price: 109},
		{id: 03, bName: 'hha', price: 40}
	]
},
computed: {
	totalPrice: function(){
          let result = 0;
          for (const book of this.books) {
            result += book.price;
          }
          return result;
        }
}
</script>

计算属性的setter 和 getter

computed: {
   fullName: function(){
       return this.firstName + ' ' + this.lastName;
   }
}        

真实写法:

computed: {
  fullName:{
	  setter(){},
	  getter: function(){
		return this.firstName + ' ' + this.lastName;
	 }
  }
}        

一般不写setter函数,所以简写为第一种写法。此时 fullName属性为只读属性。
调用fullName属性时,自动执行getter函数 。

若要使用setter,一般要传参, 接受输入的值

setter(newValue){
	const name = newValue.split(' ');
	this.firstName = name[0];
	this.lastName = name[1];
}

计算属性的缓存

计算属性内部有缓存,methods没有,所以计算属性性能更高,推荐使用

<div id = "app">
    computed: 
    <h2>{{fullName}}</h2>
    <h2>{{fullName}}</h2>
    <h2>{{fullName}}</h2>
    methods:  
    <h2>{{getFullName()}}</h2>
    <h2>{{getFullName()}}</h2>
    <h2>{{getFullName()}}</h2>
  </div>
	methods: {
        getFullName: function(){
          console.log('methods');
          return this.fN + ' ' + this.lN;
        }
      },
      computed: {
        fullName: function(){
          console.log('computed');
          return this.fN + ' ' + this.lN;
        }
      }

在这里插入图片描述
计算属性,只要涉及的值没有改变,则只计算一次,methods则每次调用都要重新计算一次

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值