利用Vue做一個小購物車

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue菜鳥之路</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
    <div id="app1">
        <div>你的購物車:</div>
        <input type="checkbox" v-model="isAll" value='true' @input="handleInputAll()"> 全選
            <div v-for="data in commodities">
                <input type="checkbox" v-model="checkArr" :value='data' @input="handleInput()"> {{ data.name }}:{{ data.price }}元  ✖️   {{ data.number }}件
                <button @click="handleClick(data,false)">-</button>
                <button @click="handleClick(data,true)">+</button>
            </div>
        總計:{{ sum }}元
    </div>
    <script>
        var app1 = new Vue({
            el:'#app1',
            data:{
                checkArr: [],
                sum: 0,
                isAll: false,
                commodities: [
                    {
                        id: "001",
                        name: "小刀",
                        number: 10,
                        price: 2

                    },
                    {
                        id: "002",
                        name: "膠水",
                        number: 200,
                        price: 5

                    },
                    {
                        id: "003",
                        name: "剪刀",
                        number: 2,
                        price: 10
                    },
                ]
            },
            methods: {
                handleInput(){
                    this.sum=0;
                    for(var i in this.checkArr){
                        this.sum+=this.checkArr[i].number*this.checkArr[i].price;
                    }
                },
                handleInputAll(){
                    this.checkArr=[]
                    if(this.isAll){
                        this.checkArr=this.commodities
                    }
                    this.handleInput()
                },
                handleClick(data,add_or_sub){   //add_or_sub爲true時增加,爲false時減少
                    temp=add_or_sub?1:-1
                    data.number+=temp
                    if(data.number<1){
                        data.number=1
                    }
                    this.handleInput()
                }
            }
        })
    </script>

</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章