组件-购物车

2018-09-18  本文已影响0人  王wl
<div class="container">
    <father></father>
</div>
<script src="js/vue.js"></script>
<script>
    Vue.component('father',{
        template:`
           <table class="table table-bordered table-hover">
                <top-title v-bind:tet='arr'></top-title>
                <bott-title v-bind:txt='fruit'></bott-title>
            </table> 
        `,
        data:function(){
            return{
                arr:['编号','名称','单价','数量','小计'],
                fruit:[
                    {uname:'香蕉',price:3,num:1,subprice:3},
                    {uname:'苹果',price:6,num:1,subprice:6},
                    {uname:'橘子',price:5,num:1,subprice:5},
                ],
            }
        }
    })
    Vue.component('top-title',{
        props:['tet'],
        template:  `
                <thead>
                    <tr  class='text-center'>
                        <th v-for='value in tet' class='text-center'>{{value}}</th>
                    </tr>
                </thead>
                `
    })
    //加减
    Vue.component('bott-title',{
        props:['txt'],
        template:`
                <tbody>
                    <tr v-for='(value,index) in txt' 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.num*value.price}}</td>
                    </tr>
                    <tr>
                        <td colspan='5' class='text-center'>总价:{{total}}元</td>
                    </tr>
                </tbody> 
        `,
        data:function(){
            return{
                total:14
            }
        },
        methods:{
            add:function(index){
                this.txt[index].num++;
                this.txt[index].subprice=this.txt[index].num*this.txt[index].price;
                this.get()
            },
            aff:function(index){
                if(this.txt[index].num>1){
                    this.txt[index].num--;
                    this.txt[index].subprice=this.txt[index].num*this.txt[index].price;
                 this.get()
                }
            },
            get:function(){
                for(var i=0,sum=0;i<this.txt.length;i++){
                    sum+=this.txt[i].subprice
                }
                this.total=sum
            }
        }
    })
    new Vue({
        el:'.container',
    })
</script>
上一篇 下一篇

猜你喜欢

热点阅读