vue 计算属性computed的使用

 1、正常传值,举一个小例子,根据列表中科目类型的比例进行计算,对对应的input值进行计算:

  

     <div class="column">
                    <el-form-item :label="'贷方比例'">
                      <el-input
                        v-model="creditRatio"
                        disabled/>
                    </el-form-item>
                  </div>
                  <div class="column">
                    <el-form-item :label="'借方比例'">
                      <el-input
                        v-model="borrowerRatio"
                        disabled/>
                    </el-form-item>
                  </div>

JS:
  computed: {
    creditRatio() {
      let data = 0
      for (let i = 0; i < this.tables.length; i++) {
        if (this.tables[i].subjectType === 1) {
          data = parseInt(data) + parseInt(this.tables[i].ratio)
        }
      }
      return data
    },
    borrowerRatio() {
      let data = 0
      for (let i = 0; i < this.tables.length; i++) {
        if (this.tables[i].subjectType === 0) {
          data = parseInt(data) + parseInt(this.tables[i].ratio)
        }
      }
      return data
    }
  },

 计算属性中的KEY不能在data()中定义,这个需要注意

2、利用卡槽进行传值

<el-table :data="tableData">
    <el-table-column label="备注" width="210" align="center">
      <template slot-scope="scope">
          <span>{{changeRemarkLength(scope.row.remark)}}</span>
      </template>
    </el-table-column>
</el-table>
 
 
<script>
    data () {
        return {
        tableData:[]
        }
    },
    methods: {
        
    },
    //计算属性
    computed:{
    //改变备注的长度,长度大于14位就用...代替剩余内容
    changeRemarkLength(){
        //text就是所传参数
        return function (text) {
        if(text.length > 14){
            return text.slice(0,14)+"...";
        }else{
            return text;
        }
        }
    }
    }
</script>


说明:

         1、计算属性传参,方法里写成 return function (val) {}形式

          2、<template slot-scope="scope">  slot-scope="scope"代表插槽的意思,这里 scope 代表行 data。scope.row取整行数据

3、computed运行机制:
computed:{
    totalPrice(){
        let totalPrice = 0
        this.listOfArticles.forEach(food => {
            totalPrice += food.price + food.count
        })
        return totalPrice // 我们只需要在模板中使用 {{ totalPrice }} 就可以表示选中的商品价格
    }
}
computed是基于它的依赖进行缓存的。computed只有在它的相关依赖发生变化才会重新计算求值。在本例子中只要价格和数量发生变化, totalPrice方法才会执行, 而只要价格和数量没有发生变化,多次访问会立即返回之前的计算结果,而不必再次执行计算。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值