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>數(shù)量</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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容