Vue 实现简单购物车总价 模板写法

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            input{
                width: 30px;
            }
        </style>
        <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <water-menu v-for="x in list" :key="x.id" v-bind:water="x"></water-menu>
            <water-total v-bind:total="list"></water-total>
        </div>
        
        <template id="water">
            <div>
                <h2>{{water.name}}</h2>
                <img v-bind:src="water.img" >
                <p>单价 : <span>{{water.price}}</span>元</p>
                <button type="button" @click="water.qty--" v-bind:disabled="water.qty==1">-</button>
                <input type="text" v-model="water.qty" />
                <button type="button" @click="water.qty++">+</button>
            </div>
        </template>
        <template id="total">
            <div>
                <p>总价 : {{sumtotal}} 元</p>
            </div>
        </template>
        
        <script type="text/javascript">
            Vue.component('waterMenu',{
                template:'#water',
                props:['water']
            })
            Vue.component('waterTotal',{
                template:'#total',
                props:['total'],
                computed:{
                    sumtotal(){
                        var total = 0;

                       // for(var i = 0;i<this.total.length;i++){
                       //    total += this.total[i]['price'] * this.total[i]['qty'];
                       // }


                        this.total.forEach(function(item){
                            total += item['price']*item['qty'];
                        })
                        return total;
                    }
                }
            })
        
        
            let vm = new Vue({
                el:'#app',
                data:{
                    list:[
                        {id:0,name:'柠檬水',img:'img/a.png',price:10,qty:1},
                        {id:1,name:'咖啡',img:'img/b.png',price:8,qty:1},
                        {id:2,name:'汽水',img:'img/c.png',price:6,qty:1},
                    ]
                }
            })
        </script>
    </body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值