2018-09-20用组件做出购物车

<div id="app">
    <boy></boy>
</div>
<script src="js/vue.js"></script>
<script>
    Vue.component("boy",{

        template:`
            <girl v-bind:love="fruit"></girl>
        `,
        data:function(){
            return{
                fruit:[
                    {name:"香蕉",price:1,num:1,sum:1},
                    {name:"苹果",price:2,num:1,sum:2},
                    {name:"鸭梨",price:3,num:1,sum:3}
                ]
            }
        }
    });

    Vue.component("girl",{
        props:["love"],
        template:`
                <table border="1" cellspacing="0" width="860px">
                    <tr>
                        <th>编号</th>
                        <th>名称</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>总价</th>
                    </tr>
                    <tr v-for="(value,index) in love">
                        <td>{{index+1}}</td>
                        <td>{{value.name}}</td>
                        <td>{{value.price}}</td>
                        <td>
                            <button @click='add(index)'>+</button>
                            {{value.num}}
                            <button @click='att(index)'>-</button>
                        </td>
                        <td>{{value.sum}}</td>
                    </tr>
                    <td colspan="5">总计:¥{{total}}</td>
                </table>
                `,
        data:function(){
            return{
                total:0
            }
        },
        methods:{

            add:function(ind){
                this.love[ind].num++;
                this.love[ind].sum = this.love[ind].num*this.love[ind].price;
                this.tot()
            },
            att:function(ind){
                if(this.love[ind].num>1){
                    this.love[ind].num--;
                }
                this.love[ind].sum = this.love[ind].num*this.love[ind].price;
                this.tot()
            },
            tot:function(){
                for(var i= 0,skr=0;i<this.love.length;i++){
                    skr+=this.love  [i].sum
                }
                this.total = skr
            }
        }
    });
    new Vue({
        el:"#app"
    });
</script>
QQ截图20180920112910.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容