Vue学习第四天(计算属性computed操作)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
    总价格为:{{AutoPrice3}}
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue ({
    el : '#app',
    computed:{
      AutoPrice:function(){
        let sumPrice=0;
        for(let i=0;i<this.books.length;i++){
          sumPrice+=this.books[i].price;
        }
         return sumPrice;
       },
        //多种for循环
        //for(let i in this.books)
        //for(let book of this.books)
      AutoPrice2: function(){
          let sumPrice=0;
          for(let i in this.books){
            sumPrice+=this.books[i].price;
          }
          return sumPrice*10;
      },

      AutoPrice3: function(){
        let sumPrice=0;
        for(let book of this.books){
          sumPrice+=book.price;
        }
        return sumPrice;
      }

    },
    data: {
      books:[
        {id:1,name:'小说1',price:119},
        {id:2,name:'小说2',price:130},
        {id:3,name:'小说3',price:200}
      ]
     }
  })
</script>
</body>
</html>

 

 

02:get  和set操作

其实我们在使用 computed操作的时候,是自动调用了get的方法,并且computed相比较method是有缓存的

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
    {{fullName}}
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue ({
    el : '#app',
    data: {
      firstName: 'FirstName',
      lastName: 'lastName'
     },
    computed: {
      fullName: {
        set:function (newValue){
          console.log("--------set------------");
          console.log(newValue);
          let names=newValue.split(" ");
          console.log(names);
          this.firstName=names[0];
          this.lastName=names[1];
        },
        get: function(){
          return this.firstName+"--------"+this.lastName
        }
      }
    }
    //computed和methods区别
    //methods方法,方法掉几次就会执行几次方法,效率比较低下
    //computed函数:只要 调的元素值不会发生变化,只会执行一次。但当值发生改变的时候,会重新调用一次该函数
    //computed 效率高,会有缓存的原因存在
  })
</script>
</body>
</html>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值