利用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>
发布了129 篇原创文章 · 获赞 57 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/NetRookieX/article/details/104903779