vue购物车效果

2018-09-17  本文已影响0人  王wl

html部分

<div class="container">
   <table class="table table-bordered table-hover">
       <thead>
           <tr class='text-center'>
               <th class='text-center'>编号</th>
               <th class='text-center'>名称</th>
               <th class='text-center'>单价</th>
               <th class='text-center'>数量</th>
               <th class='text-center'>小计</th>
           </tr>
       </thead>
       <tbody>
           <tr v-for='(value,index) in fruit' class="text-center">
               <td>{{index+1}}</td>
               <td>{{value.uname}}</td>
               <td>{{value.price}}</td>
               <td><button @click='add(index)'>+</button><span>{{value.num}}</span><button @click='aff(index)'>-</button></td>
               <td>{{value.price*value.num}}</td>
           </tr>
       </tbody>
       <tfoot>
           <tr>
               <td colspan="5" class="text-center">总计:{{total}}</td>
           </tr>
       </tfoot>
   </table>

js部分

<script src="js/vue.js"></script>
<script>
    new Vue({
        el:'.container',
        data:{
            fruit:[
                {uname:'香蕉',price:3,num:1,subprice:3},
                {uname:'苹果',price:6,num:1,subprice:6},
                {uname:'鸭梨',price:5,num:1,subprice:5},
            ],
            total:14
        },
        methods:{
            add:function(index){
                this.fruit[index].num++;
                this.getTotal()
                this.fruit[index].subprice=this.fruit[index].price*this.fruit[index].num;
            },
            aff:function(index){
                if(this.fruit[index].num>1){
                    this.fruit[index].num--;
                }
                this.getTotal()
            },
            getTotal:function(){
                for(var i=0,sum=0;i<this.fruit.length;i++){
                    sum+=this.fruit[i].subprice
                }
                this.total=sum
            }
        }
    })
</script>
上一篇 下一篇

猜你喜欢

热点阅读