Vue初学04-计算属性

计算属性computed,可以将属性进行拼接,计算生成新的属性,计算属性的结果会被缓存,效率较高。

属性拼接

通过computed可以将多个属性拼接到一起,返回一个新的属性,避免用{{mustache}}语法拼接。用computed可以将结果缓存,比methods效率高。如下所示,将data中的三个属性拼接到一起返回。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="../js/vue.js"></script>
</head>
<body>

      <div id="app">
            <p>{{allwords}}</p>
      </div>

    <script>
         const vue = new Vue({
             el:"#app",
             data:{
                 firstword:"hello",
                 secondword:"vue",
                 thirdword:"!"
             },
             computed:{
                 allwords:function(){
                     return this.firstword+" " +this.secondword+this.thirdword
                 }
             }
         });
    </script>
</body>
</html>

属性计算

通过computed还可以计算生成一个新的属性,如下所示,通过计算属性,返回所有书的总价格。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="../js/vue.js"></script>
</head>
<body>

      <div id="app">
            <p>总价格:{{totalprice}}</p>
      </div>

    <script>
         const vue = new Vue({
             el:"#app",
             data:{
                 books:[{name:'哈利波特与死亡圣器',price:'50',count:'2'},
                     {name:'老人与海',price:'50',count:'3'},
                     {name:'三个火枪手',price:'50',count:'2'}]
             },
             computed:{
                 totalprice:function(){
                     let total=0;
                     for(let i=0;i<this.books.length;i++)
                     {
                         total+=this.books[i].price*this.books[i].count;
                     }
                     return total;
                 }
             }
         });
    </script>
</body>
</html>

效果如下

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值