计算属性computed

计算属性的基本使用

案例拼接firstName和lastName
可以用methods中的方法实现

<h2>{{getFullName()}}</h2>
......
methods:{
      getFullName() {
        return this.firstName + ' ' + this.lastName
      }
    }

现在用计算属性实现

<h2>{{fullName}}</h2>
......
computed:{
      fullName(){
        return this.firstName + ' ' + this.lastName
      }
    }

问题:二者代码区别不大,为什么要选择用计算属性?

选择计算属性的原因

计算属性具有缓存,在不改变变量只重复使用时,计算属性只会调用一次,而methods中的方法使用几次就调用几次
案例:计算总价格并多次调用

data: {
      books: [
        {id:110,name:'Unix编程', price:119},
        {id:111,name:'代码大全', price:105},
        {id:112,name:'深入理解计算机原理', price:98},
        {id:113,name:'现代操作系统', price:87},
      ]
    },
  • 用methods中的方法:
<h2>总价格:{{getTotalPrice}}</h2>
  <h2>总价格:{{getTotalPrice}}</h2>
  <h2>总价格:{{getTotalPrice}}</h2>
  <h2>总价格:{{getTotalPrice}}</h2>
  ......
  methods: {
      getTotalPrice:function (){
        let result = 0
        for (let i=0;i<this.books.length; i++){
          result += this.books[i].price
        }
        return result
      }
    },

在控制台可以看到打印次数为4次

  • 用计算属性实现
<h2>总价格:{{totalPrice}}</h2>
  <h2>总价格:{{totalPrice}}</h2>
  <h2>总价格:{{totalPrice}}</h2>
  <h2>总价格:{{totalPrice}}</h2>
  ......
   computed:{
      totalPrice(){
        let result = 0
        for (let i=0;i<this.books.length; i++){
          result += this.books[i].price
        }
        return result
    }

在控制台可看出调用了4次,只打印了一次

computed的set/get方法

使用计算属性时,不加()的原因,就像Java实体类中的属性一样,具有get/set方法,
一般不设置set方法,为只读属性

computed:{
      //完整的计算属性
      fullName: {
        //一般不设置set方法,只读属性
        set:function (newValue){
           console.log('--------',newValue);
        },
        get:function (){
          return this.firstName+ ' ' + this.lastName;
        }
      }
    }

简化后:

computed:{
      //简化后的计算属性
      fullName() {
         return this.firstName+ ' ' + this.lastName;
       }
    }

学习视频链接

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值